tags:

views:

695

answers:

2

I was trying a 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)
{
  Utils.LogMessageToFile("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?

A: 

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

cornerback84
It is a workaround, but highly not recommended.
Lex Li
+7  A: 

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

dtb
+1... or you could use the address family from the IPAddress, of course...
Roger Lipscombe
IP v4 and v6 have a lot of differences. Since Windows 7, you need to learn both as they have impact on your socket programming.
Lex Li
any documents/links where these differences regarding to socket programming are listed? they would come in handy
Amitd