how to change originating IP in HttpWebRequest

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 🙂

Leave a Comment