SocketException: 地址与请求的协议不兼容 [英] SocketException: address incompatible with requested protocol

查看:48
本文介绍了SocketException: 地址与请求的协议不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

代码片段是:

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

以上代码在 Win-XP sp3 中运行良好.

The above code works fine in Win-XP sp3 .

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

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.

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

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

更改您的代码以创建套接字以使用指定 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);
                        ↑

注意:获取localhost的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).

这篇关于SocketException: 地址与请求的协议不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆