唐英荣*_*唐英荣 12 .net c# webrequest ip-address
我有一个多IP地址的服务器.现在我需要使用http协议与多个服务器通信.每个服务器只接受来自我的服务器的指定IP地址的请求.但是在.NET中使用WebRequest(或HttpWebRequest)时,请求对象将自动选择IP地址.无论如何我都找不到用地址绑定请求.
反正有没有这样做?或者我必须自己实施webrequest课程?
Sam*_*eff 14
您需要使用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();
}
Run Code Online (Sandbox Code Playgroud)
如果你想使用WebClient你需要子类化它:
var webClient = new WebClient2(IPAddress.Parse("10.0.0.2"));
Run Code Online (Sandbox Code Playgroud)
和子类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
(感谢@Samuel所有重要的ServicePoint.BindIPEndPointDelegate部分)
| 归档时间: |
|
| 查看次数: |
18891 次 |
| 最近记录: |