绑定IP地址只是第一次使用
|
我想从服务器上的可用IP地址之一发出Web请求,所以我使用了此类:
public class UseIP
{
public string IP { get; private set; }
public UseIP(string IP)
{
this.IP = IP;
}
public HttpWebRequest CreateWebRequest(Uri uri)
{
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
return WebRequest.Create(uri) as HttpWebRequest;
}
private IPEndPoint Bind(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
IPAddress address = IPAddress.Parse(this.IP);
return new IPEndPoint(address, 0);
}
}
然后:
UseIP useIP = new UseIP(\"Valid IP address here...\");
Uri uri = new Uri(\"http://ip.nefsc.noaa.gov\");
HttpWebRequest request = useIP.CreateWebRequest(uri);
// Then make the request with the specified IP address
但是该解决方案仅在第一时间有效!
没有找到相关结果
已邀请:
4 个回复
骂狮淋唐便
以下(基本)测试结果将为每个请求调用Bind委托:
辰炔诚薯
而且据我所知,端点是缓存的,因此即使清除委托在某些情况下也可能不起作用,并且无论如何它们都可能会被重置。在最坏的情况下,您可能会卸载/重新加载应用程序域。
浮凰量
我这样做是因为: 我认为对
的调用实际上使用\“ default \” ip来执行请求,甚至没有调用绑定委托到您指定的URI。至少在我的机器上,没有以您提出的方式调用ѭ7(我知道请求是因为我没有设置Proxy并收到代理身份验证错误); 在ServicePointManager的文档中,它声明\“如果该主机和方案存在现有的ServicePoint对象,则ServicePointManager对象将返回现有的ServicePoint对象;否则,该ServicePointManager对象将创建一个新的ServicePoint对象\”可能会始终返回如果URI相同,则返回相同的ServicePoint(也许可以解释为什么随后的调用在同一EndPoint中进行)。 这样,我们可以确保,即使已经请求URI,它也将使用所需的IP,而不是使用
的某些先前的“缓存”。
蔬谢窗港
re:Bind方法被多次调用。 对我有用的是在添加任何委托链接之前将其删除。
我也喜欢缓存UseIP对象的想法。因此,我将此静态方法添加到UseIP类。