简体   繁体   中英

An address incompatible with the requested protocol was used

I am running network related Windows project in Visual Studio 2012 and Operating System is Windows 7. I am getting the following error:

An address incompatible with the requested protocol was used

My code is:

public DestCode()
{
   IPHostEntry ipEntry = Dns.GetHostEntry(Environment.MachineName);
   IPAddress IpAddr = ipEntry.AddressList[0];
   ipEnd = new IPEndPoint(IpAddr, 5001);
   sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
   sock.Bind(ipEnd);
}

It's very likely that ipEntry.AddressList[0] is never the right thing to do. A single machine may have a few IP addresses configured, some of which are auto-configured, and would not normally be used by an application. There could be IPv4 addresses, IPv6 addresses, link-scoped addresses, site-scoped addresses, and then somewhere, maybe finally a global-scoped address (one that can be used on the public internet).

For instance, this is what my current machine has:

在此处输入图片说明

You'll note that the list seems to prefer to sort IPv6 addresses to lower indexes. It is very likely that the same is occurring on your machine.

You create your socket using AddressFamily.InterNetwork , which indicated IPv4, but then you bind with an address that is very likely IPv6:

new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
sock.Bind(ipEnd);

If you wanted to make the code 'work' with as few changes, then provide the address family of the address you want to bind to when creating the socket, as so:

new Socket(ipEnd.AddressFamily, SocketType.Stream, ProtocolType.IP)
sock.Bind(ipEnd);

However, using ipEntry.AddressList[0] is probably the wrong thing to do, since you'll never know which address you'll get. So how do you get your address? Well, that depends on you. If you want to just loopback for testing or doing some IPC, use 127.0.0.1 ; if you want to send and receive on any address, bind to 0.0.0.0 , which means the 'any' address in this particular context. Otherwise, it's typical to take that sort of configuration from the user, especially in the case that the user knows what interface he wants it to listen on. In my case, there's no one good interface to pick automatically, and I surely would want you to ask me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM