Search code examples
c#.netweb-serviceswebrequest

Change originating IP - circumventing caching of connections


I need to call the same API many times, but with different IP's based on certain parameters.

I've implemented the code in this SO question: how to change originating IP in HttpWebRequest

This worked well when I needed to specify a single IP for the API I am calling, but now I need to use from several IPs based on my requirements, and this method no longer seems to work. The API URL seems to be cached and subsequent calls will use that IP, instead of the specific one I wish to set on every call.

I need a method that will let me very specifically choose the source IP for each request.

Adding:

If I split my application into two separate apps, each one using its own source ip, would this be a brute force approach to force it to work? in other words, is the caching performed only per process? (I assume this is so).


Solution

  • Using HttpWebRequest.ConnectionGroupName you should be able to get around the ServicePoint connection reuse.

    var hr = (HttpWebRequest)WebRequest.Create("http://google.com?");
    hr.ConnectionGroupName = hr.RequestUri.ToString(); //Different connection pool per url. Might be better to make this random.
    hr.GetResponse();
    

    Alternatively you can just force close the group using ServicePoint.CloseConnectionGroup. The default group is null.

    var hr = (HttpWebRequest)WebRequest.Create("http://google.com");
    hr.ServicePoint.CloseConnectionGroup(null);
    hr.GetResponse();