Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose WebClient outgoing IP [duplicate]

Tags:

c#

.net

webclient

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)

like image 960
Tim Avatar asked May 03 '26 18:05

Tim


1 Answers

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())
{
   ...
}
like image 66
Darin Dimitrov Avatar answered May 05 '26 07:05

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!