Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

c# - SocketException: address incompatible with requested protocol

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

System.Net.Sockets.SocketException: An address incompatible with the requested protocol was used.
Error Code: 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 .

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

Anyone has encountered similar problems? Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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);
                        ↑

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...