Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

c# - how to change originating IP in HttpWebRequest

I'm running this application on a server that has assigned 5 IPs. I use HttpWebRequest to fetch some data from a website. But when I make the connection I have be able to specify which one of the 5 IPs to make the connection from. Does HttpWebRequest support this? If it doesn't can I inherit a class from it to change it's behavior? I need so ideas here.

My code right now is something like:

System.Net.WebRequest request = System.Net.WebRequest.Create(link);
((HttpWebRequest)request).Referer = "http://application.com";
using (System.Net.WebResponse response = request.GetResponse())
{
    StreamReader sr = new StreamReader(response.GetResponseStream());
    return sr.ReadToEnd();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to this, no. You may have to drop down to using Sockets, where I know you can choose the local IP.

EDIT: actually, it seems that it may be possible. HttpWebRequest has a ServicePoint Property, which in turn has BindIPEndPointDelegate, which may be what you're looking for.

Give me a minute, I'm going to whip up an example...

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");

req.ServicePoint.BindIPEndPointDelegate = delegate(
    ServicePoint servicePoint,
    IPEndPoint remoteEndPoint,
    int retryCount) {

    if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) {
        return new IPEndPoint(IPAddress.IPv6Any, 0);
    } else {
        return new IPEndPoint(IPAddress.Any, 0);
    }

};

Console.WriteLine(req.GetResponse().ResponseUri);

Basically, the delegate has to return an IPEndPoint. You can pick whatever you want, but if it can't bind to it, it'll call the delegate again, up to int.MAX_VALUE times. That's why I included code to handle IPv6, since IPAddress.Any is IPv4.

If you don't care about IPv6, you can get rid of that. Also, I leave the actual choosing of the IPAddress as an exercise to the reader :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...