2010-11-25 80 views
12

我有一个多IP地址的服务器。现在我需要使用http协议与几台服务器进行通信。每个服务器只接受来自我的服务器的指定IP地址的请求。但是在.NET中使用WebRequest(或HttpWebRequest)时,请求对象会自动选择一个IP地址。无论如何,我无法找到将请求与地址绑定的地方。我可以使用.NET Framework从指定的IP地址发送webrequest吗?

有无论如何这样做吗?或者我必须自己实施一个webrequest课程?

回答

12

您需要使用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(); 

} 
+1

令人惊叹。问题就这样简单地解决了!谢谢,山姆。 – 2010-11-25 11:25:46

6

如果你想做到这一点使用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部分)

相关问题