servers with multiple ips and HttpWebRequest

I’ve been working on a windows service that uses HttpWebRequest to scrape some data from a website. It was however important to use a certain IP from the 5 that the server had, and never touch the rest of them. The HttpWebRequest class doesn’t seem to provide with an obvious way to do this, or expose the socket it’s using for the connections.

Right when I was about to write my own HttpWebRequest class using nothing but sockets, I stumbled on the  ServicePoint.BindIPEndPointDelegate property. Aparently you can use that to set a callback at the time the socket receives it’s IP, and change it.

You can do something like this:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://MyServer");
request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Then just declare the callback, and return any local IP you want.

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
     return new IPEndPoint(IPAddress.Any,5000);
}

Also make sure you check the addressfamily of the remoteEndPoint. If your request goes to ipv6 don’t return an ipv4 ip :))

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: