2012-07-09 93 views
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

如何使這項工作?

回答

2

它看起來像你的終點的端口號在該行設置爲零:除非這得到改變以後

lastIpEndpoint = new IPEndPoint(candidates[rnd.Next(candidates.Count())],0); 

,這是不可能的,你將能夠連接到一個HTTP服務器上。您可能能夠使用remoteEndPoint中包含的端口,或者如果它是衆所周知的(例如,對於在默認端口上運行的HTTP服務器,則可以使用80),也可以硬編碼該端口號。

lastIpEndpoint = new IPEndPoint(candidates[rnd.Next(candidates.Count())], remoteEndPoint.Port); 
+0

實際上,這不起作用。我試過解決方案,我仍然「無法連接到遠程服務器---> System.Net.Sockets.SocketException:請求的地址在其上下文無效173.194.39.68:80」(我在谷歌上測試這個) – 2012-07-13 15:11:23

+0

@ArsenZahray你用什麼端口號?你硬編碼80,還是使用remoteEndPoint.Port? – 2012-07-13 15:25:52

+0

@ArsenZahray這個錯誤通常意味着IP地址不屬於機器 - 這是因爲您正在使用'Dns.GetHostName()',因此我現在正在撓頭。 – 2012-07-13 15:44:08