1
當我已經有了C#代碼具有多個IP地址的計算機上運行,而我有下面的代碼來選擇一個HttpWebRequest的一個IP地址連接到遠程服務器:無法選擇IpEndPoint
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();
}
此代碼應該選擇avaliable IP列表隨機IP,比堅持下去。
取而代之的是,每次我用它發送請求的時候,我發現了以下情況例外:
Unable to connect to the remote server
如何使這項工作?
實際上,這不起作用。我試過解決方案,我仍然「無法連接到遠程服務器---> System.Net.Sockets.SocketException:請求的地址在其上下文無效173.194.39.68:80」(我在谷歌上測試這個) – 2012-07-13 15:11:23
@ArsenZahray你用什麼端口號?你硬編碼80,還是使用remoteEndPoint.Port? – 2012-07-13 15:25:52
@ArsenZahray這個錯誤通常意味着IP地址不屬於機器 - 這是因爲您正在使用'Dns.GetHostName()',因此我現在正在撓頭。 – 2012-07-13 15:44:08