13

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 ?

Matt
  • 22,721
  • 17
  • 71
  • 112
唐英荣
  • 305
  • 2
  • 4
  • 15

3 Answers3

15

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();

}
Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
  • 1
    Amazing. The problem just got resolved in such a simple way! Thanks, Sam. – 唐英荣 Nov 25 '10 at 11:25
  • I don't recommend setting the port to 5000. This can cause timeouts if you are making requests with multiple instances on this port. Instead, I would set the port to 0 and let the tcp layer handle the connections, which will always be through port 80 anyway. – Mike Oct 18 '16 at 16:28
  • It works fine on .NET Framework but doesn't work on .NET Core and I don't know why. – Max Jacobi Mar 30 '21 at 15:26
7

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)

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
2

Not sure whether you read this post (?)

How to specify server IP in HttpWebRequest

or

Specifying Source IP of HttpWebRequest

Shoban
  • 22,920
  • 8
  • 63
  • 107