客户端套接字"no connection could be made..."上的 C# 客户端-服务器实现错误



我正在尝试启动我的客户端,但遇到错误。服务器已在同一台计算机上运行。所以我在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 地址?

可以使用 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);    

我用于 IPV4 的本地主机:

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

最新更新