3

My .net app uses WebClient to access files on the internet and my machine has multiple IP addresses. Is there a way to programatically select which IP to use instead of the first IP when making outbound requests? (doesn't have to be WebClient)

Tim
  • 109
  • 2
  • 6
  • 1
    You literally [asked the same question yesterday](http://stackoverflow.com/questions/28792674/choose-outgoing-ip-on-a-machine-with-multiple-ip-addresses). Of course most of the comments there are dead wrong, but one pointed you to a [relevant Q&A](http://stackoverflow.com/questions/5870191/sending-httpwebrequest-through-a-specific-network-adapter). Done any research since then? Check `ServicePoint.BindIPEndPointDelegate`. See [duplicate](http://stackoverflow.com/questions/4273462/can-i-send-webrequest-from-specified-ip-address-with-net-framework). – CodeCaster Mar 02 '15 at 11:57
  • i saw that but wanted to ask if it would be possible with just webclient – Tim Mar 02 '15 at 12:10
  • Yeah then inherit from WebClient and use `protected override GetWebRequest()` to add that logic. – CodeCaster Mar 02 '15 at 12:13

1 Answers1

2

One possibility to achieve this is to use the ServicePoint.BindIPEndPointDelegate event and specify which IP address to use.

Example:

var uri = new Uri("YOUR URI");
var servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = (sp, remoteEndPoint, retryCount) =>
{
    var address = IPAddress.Parse("PUT YOUR DESIRED IP HERE");
    return new IPEndPoint(address, 0);
};

Now try making the HTTP request to the corresponding url.

Alternatively if you are using an HttpWebrequest you could assign this per delegate per request:

var request = (HttpWebRequest)WebRequest.Create("YOUR URI");
request.ServicePoint.BindIPEndPointDelegate = (sp, remoteEndPoint, retryCount) =>
{
    var address = IPAddress.Parse("PUT YOUR DESIRED IP HERE");
    return new IPEndPoint(address, 0);
};

using (var response = request.GetResponse())
{
   ...
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928