Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing which IP the HTTP request is using when having multiple IPs (.NET)

Tags:

c#

.net

vb.net

ip

I am writing a .NET program which will run on a computer with several IP addresses. The program makes HTTP requests to given web addresses. I want to choose which IP address I use (so I can determine which IP address will appear on the log of the other server).

Suggestions?

like image 554
Ramon Snir Avatar asked Apr 01 '11 14:04

Ramon Snir


1 Answers

I believe you can force the local endpoint by providing a BindIPEndPointDelegate which supplies the IP/port to bind to.

string sendingIp = "192.168.0.1";
int sendingPort = 5000;
Uri uri = new Uri("http://google.com");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri);
ServicePoint sp = ServicePointManager.FindServicePoint(uri);
sp.BindIPEndPointDelegate =
    (servicePoint,remoteEp,retryCount) =>
         {
             return new IPEndPoint(IPAddress.Parse(sendingIp),sendingPort);
         };
var data = new StreamReader(wr.GetResponse().GetResponseStream()).ReadToEnd();

This code doesn't deal with disposal correctly.

like image 196
spender Avatar answered Oct 14 '22 09:10

spender