Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 853
Tudor Carean Avatar asked Jul 27 '10 15:07

Tudor Carean


2 Answers

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 :)

like image 115
Mike Caron Avatar answered Nov 20 '22 18:11

Mike Caron


Try this:

System.Net.WebRequest request = System.Net.WebRequest.Create(link);
request.ConnectionGroupName = "MyNameForThisGroup"; 
((HttpWebRequest)request).Referer = "http://application.com";
using (System.Net.WebResponse response = request.GetResponse())
{
    StreamReader sr = new StreamReader(response.GetResponseStream());
    return sr.ReadToEnd();
}

Then try setting the ConnectionGroupName to something distinct per source ip you wish to use.

edit: use this in conjunction with the IP binding delegate from the answer above.

like image 1
Brady Moritz Avatar answered Nov 20 '22 17:11

Brady Moritz