SocketException:地址与请求的协议不兼容不兼容、协议、地址、SocketException

2023-09-02 20:47:08 作者:大海蓝天我的少年

我试图运行Win7-64bit机器上的净套接字服务器code。 我不断收到以下错误:

I was trying to run a .Net socket server code on Win7-64bit machine . I keep getting the following error:

System.Net.Sockets.SocketException:一个地址与请求的协议不兼容   被使用。   错误code:10047

System.Net.Sockets.SocketException: An address incompatible with the requested protocol was used. Error Code: 10047

在code段是:

IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
IPEndPoint ip = new IPEndPoint(ipAddress, 9989);
Socket serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
try
{
    serverSocket.Bind(ip);
    serverSocket.Listen(10);
    serverSocket.BeginAccept(new AsyncCallback(AcceptConn), serverSocket);           
}
catch (SocketException excep)
{
  Log("Native code:"+excep.NativeErrorCode);
 // throw;
}    

以上code正常工作在Win-XP SP3。

The above code works fine in Win-XP sp3 .

我已经检查的MSDN 错误code细节但它并没有多大意义了我。

I have checked Error code details on MSDN but it doesn't make much sense to me.

任何人都遇到类似的问题?任何帮助?

Anyone has encountered similar problems? Any help?

推荐答案

在Windows Vista(和Windows 7),Dns.GetHostEntry也会返回IPv6地址。你的情况,IPv6地址(:: 1)首先在列表中。

On Windows Vista (and Windows 7), Dns.GetHostEntry also returns IPv6 addresses. In your case, the IPv6 address (::1) is first in the list.

您无法连接到IPv6(InterNetworkV6)使用IPv4(网际网络)插座解决。

You cannot connect to an IPv6 (InterNetworkV6) address with an IPv4 (InterNetwork) socket.

更改code创建套接字使用指定的IP地址的地址族:

Change your code to create the socket to use the address family of the specified IP address:

Socket serverSocket =
    new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        ↑

注意:有一个捷径获得的本地主机的IP地址:您可以简单地使用IPAddress.Loopback (127.0.0.1)或者IPAddress.IPv6Loopback (:: 1)。

Note: There's a shortcut to obtain the IP address of localhost: You can simply use IPAddress.Loopback (127.0.0.1) or IPAddress.IPv6Loopback (::1).