客户端套接字上的C#Client-Server实现错误“无法建立连接...”

时间:2012-06-15 15:13:32

标签: c# sockets

我正在尝试启动我的客户端,但有错误。服务器已在同一台计算机上运行。所以我在GetHostEntry中使用“localhost”:

 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地址?

2 个答案:

答案 0 :(得分:2)

您可以使用IPAddress类的AddressFamily属性来判断该地址是IPv4还是IPv6。

通过这种方式,您可以遍历返回的IPAddress-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);    

答案 1 :(得分:-1)

我用于IPV4的localhost:

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