我可以使用.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

在与httpwebrequest关联的套接字尝试连接到远程端之前调用该委托。

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

如果您想使用WebClient执行此操作,则需要对其进行子类化:

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

和子类:

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

(感谢@Samuel所有重要的ServicePoint.BindIPEndPointDelegate部分)

不确定你是否看过这篇文章(?)

如何在HttpWebRequest中指定服务器IP

要么

指定HttpWebRequest的源IP