C# · 12月 30, 2021

c# – 可以使用.NET Framework从指定的ip地址发送webrequest吗?

我有一个服务器与多个IP地址.现在我需要与几个服务器通信http协议.每个服务器只接受来自我服务器的指定ip地址的请求.但是当在.NET中使用WebRequest(或HttpWebRequest)时,请求对象将自动选择一个IP地址.我找不到要用地址绑定请求.

有没有这样做?或者我必须自己实现一个webrequest类?

解决方法 您需要使用ServicePoint.BindIPEndPointDelegate回调.

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