0

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

4

2 回答 2

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);    
于 2012-06-15T15:16:48.453 回答
-1

我用于 IPV4 的本地主机:

IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[1];
于 2012-06-15T15:23:50.607 回答