2012-06-15 65 views
0

我試圖啓動我的客戶端,但出現錯誤。服務器已經在同一臺計算機上運行。所以我使用「本地主機」與GetHostEntry:客戶端套接字上的C#客戶端 - 服務器實現錯誤「無法建立連接...」

IPHostEntry ipHostInfo = System.Net.Dns.GetHostEntry("localhost"); 
IPAddress ipAddress = ipHostInfo.AddressList[0]; 
IPEndPoint remoteEP = new IPEndPoint(ipAddress, Port); 

Sock = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
Sock.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), Sock); 

但我有這個「無連接可以作出,因爲目標機器積極拒絕」:

System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [::1]:7777 
    at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) 
    at NotifierClient.AsynchronousClient.ConnectCallback(IAsyncResult ar) in *** :line 156 

156線是

client.EndConnect(ar); 

是什麼原因?難道是因爲ipHostInfo.AddressList [0]是IPv6嗎?那我怎麼可以接受IPV4地址?

+0

莫非它是你的防火牆阻止它? –

+0

我覺得沒有。服務器工作正常。和VS有權使用網絡 – Ksice

+0

順便說一句,我可以簡單地通過telnet連接到我的服務器 – Ksice

回答

2

您可以使用IPAddress類的AddressFamily屬性來判斷地址是IPv4還是IPv6。

這樣你就可以遍歷列表ip地址-ES返回,選擇第一個是IPv4地址:

IPHostEntry ipHostInfo = System.Net.Dns.GetHostEntry("localhost");  

IPAddress ipAddress = null; 
foreach(var addr in ipHostInfo.AddressList) 
{ 
    if(addr.AddressFamily == AddressFamily.InterNetwork)  // this is IPv4 
    { 
     ipAddress = addr; 
     break; 
    } 
} 

// at this point, ipAddress is either going to be set to the first IPv4 address 
// or it is going to be null if no IPv4 address was found in the list 
if(ipAddress == null) 
    throw new Exception("Error finding an IPv4 address for localhost"); 

IPEndPoint remoteEP = new IPEndPoint(ipAddress, Port); 

Sock = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
Sock.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), Sock);  
+0

我已經這麼做了。請在代碼 – Ksice

+0

@Ksice中看到我的新增內容 - 你做得不對,請參閱我的回答編輯 –

+0

哦,那就是你的意思。謝謝!這有幫助! – Ksice

-1

我使用本地主機的IPV4:

IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost"); 
IPAddress ipAddress = ipHostInfo.AddressList[1]; 
+0

該代碼可能會爲您啓動。無法保證IPv4地址將列在第二位..更糟糕的是,不能保證IPv4地址甚至會存在! –