我在具有多个 IP 地址的计算机上运行了 c# 代码,并且我有以下代码来为 httpWebRequest 选择 IP 地址:
class Interact
{
<data, cookies, etc>
HttpWebRequest CreateWebRequest(...)
{
.....
request.ServicePoint.BindIPEndPointDelegate = delegate(
ServicePoint servicePoint,
IPEndPoint remoteEndPoint,
int retryCount)
{
if (lastIpEndpoint!=null)
{
return lastIpEndpoint;
}
var candidates =
GetAddresses(remoteEndPoint.AddressFamily);
if (candidates==null||candidates.Count()==0)
{
throw new NotImplementedException();
}
return
lastIpEndpoint = new IPEndPoint(candidates[rnd.Next(candidates.Count())],0);
};
};
return request;
}
}
这是GetAddresses的代码:
static IPAddress[] GetAddresses(AddressFamily af)
{
System.Net.IPHostEntry _IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
return (from i in _IPHostEntry.AddressList where i.AddressFamily == af select i).ToArray();
}
此代码应该从可用 IP 列表中选择一个随机 IP,然后坚持使用它。
相反,每次我用它发送请求时,我都会收到以下异常:
Unable to connect to the remote server
我该如何进行这项工作?