我已经在具有多个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
我如何使这项工作?
答案 0 :(得分:2)
看起来您在行中将结束点的端口号设置为零:
lastIpEndpoint = new IPEndPoint(candidates[rnd.Next(candidates.Count())],0);
除非以后更改,否则您不太可能连接到端口0上的HTTP服务器。您可以使用remoteEndPoint
中包含的端口,或者您可能很难如果众所周知,则对端口号进行编码(例如,对于在默认端口上运行的HTTP服务器为80)。
lastIpEndpoint = new IPEndPoint(candidates[rnd.Next(candidates.Count())], remoteEndPoint.Port);