Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I send webrequest from specified ip address with .NET Framework?

I have a server with multi ip addresses. Now I need to communicate with several servers with http protocol. Each server only accept the request from a specified ip address of my server. But when using WebRequest(or HttpWebRequest) in .NET , the request object will choose a ip address automatically. I can't find anyway to bind the request with a address.

Is there anyway to do so ? Or I have to implement a webrequest class myself ?

like image 725
唐英荣 Avatar asked Nov 25 '10 03:11

唐英荣


3 Answers

If you want to do this using WebClient you'll need to subclass it:

var webClient = new WebClient2(IPAddress.Parse("10.0.0.2"));

and the subclass:

public class WebClient2 : WebClient
{
    public WebClient2(IPAddress ipAddress) {
        _ipAddress = ipAddress;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = (WebRequest)base.GetWebRequest(address);

        ((HttpWebRequest)request).ServicePoint.BindIPEndPointDelegate += (servicePoint, remoteEndPoint, retryCount) => {

            return new IPEndPoint(_ipAddress, 0);
        };

        return request;
    }
}

(thanks @Samuel for the all important ServicePoint.BindIPEndPointDelegate part)

like image 158
Simon_Weaver Avatar answered Nov 20 '22 14:11

Simon_Weaver


You need to use the ServicePoint.BindIPEndPointDelegate callback.

http://blogs.msdn.com/b/malarch/archive/2005/09/13/466664.aspx

The delegate is called before the socket associated with the httpwebrequest attempts to connect to the remote end.

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
    Console.WriteLine("BindIPEndpoint called");
      return new IPEndPoint(IPAddress.Any,5000);

}

public static void Main()
{

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://MyServer");

    request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

}
like image 22
Samuel Neff Avatar answered Nov 20 '22 14:11

Samuel Neff


Not sure whether you read this post (?)

How to specify server IP in HttpWebRequest

or

Specifying Source IP of HttpWebRequest

like image 2
Shoban Avatar answered Nov 20 '22 14:11

Shoban