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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2370388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:50:14  来源:igfitidea点击:

SocketException: address incompatible with requested protocol

c#.netsockets

提问by Amitd

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

我试图在 Win7-64 位机器上运行 .Net 套接字服务器代码。
我不断收到以下错误:

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

System.Net.Sockets.SocketException: 使用了与请求的协议不兼容的地址。
错误代码:10047

The code snippet is :

代码片段是:

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;
}    

The above code works fine in Win-XP sp3 .

上面的代码在 Win-XP sp3 中工作正常。

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

我已经在 MSDN 上检查了错误代码详细信息,但对我来说没有多大意义。

Anyone has encountered similar problems? Any help?

有人遇到过类似的问题吗?有什么帮助吗?

采纳答案by dtb

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

在 Windows Vista(和 Windows 7)上,Dns.GetHostEntry 还返回 IPv6 地址。在您的情况下,IPv6 地址 (::1) 是列表中的第一个。

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

您无法使用 IPv4 (InterNetwork) 套接字连接到 IPv6 (InterNetworkV6) 地址。

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

更改您的代码以创建套接字以使用指定 IP 地址的地址族:

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

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).

注意:有一个快捷方式可以获取localhost的 IP 地址:您可以简单地使用IPAddress.Loopback(127.0.0.1) 或IPAddress.IPv6Loopback(::1)。

回答by ata

Edit C:\Windows\System32\drivers\etc\hosts and add the line "127.0.0.1 localhost" (if its not there, excluding quotes)

编辑 C:\Windows\System32\drivers\etc\hosts 并添加行“127.0.0.1 localhost”(如果不存在,不包括引号)