Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
513 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...