How to listen on multiple IP addresses?

2020-06-16 03:01发布

问题:

If my server has multiple IP addresses assigned to it, and I would like to listen to some (or all) of them, how do I go about doing that?

Do I need to create a new socket for each IP address, and bind it? Can i bind multiple ip addresses to a single socket? Does IPAddress.Any listen on all IP addresses? The MSDN library is very unclear on this matter.

回答1:

You cannot bind a single socket to multiple endpoints. A SocketException (invalid argument error) occurs the second time you call Bind() for a given socket.

As others have said, you can use IPAddress.Any to listen to the IPv4 addresses on the local machine. However, if you only want to listen on a subset of the available IP addresses, you'll have to create separate sockets.



回答2:

Technically, your server never has any IP addresses assigned to it.

Instead, individual network interfaces may be assigned IP addresses. Usually, each NIC gets one IP address, but that's just the most common case.

If you want to control which interfaces are listening for incoming connections on your chosen port, you'll need to create a separate socket for each one.



回答3:

I have worked on it, IPAddress.Any is not the proper way, It will bind any Suitable IP address. In my case I have 2 NIC and I couldn't trouble shoot the problem. When I added

System.Net.IPAddress ipAddress = IPAddress.Parse("xxx.xxx.xxx.xxx");
listener = new TcpListener(ipAddress, portNum);

It worked fine.



回答4:

If you want to listen on all IPv4 and IPv6 addresses, use this code:

var listener = new TcpListener(IPAddress.IPv6Any, port);
listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

IPv6Any tells Windows to listen on the IPv6 stack. Setting the socket option to false tells Windows to not limit itself to the IPv6 stack, but rather to also listen on the IPv4 stack. The default is to only listen on the stack explicitly specified.



回答5:

Yes, IPAddress.Any will listen on all interfaces.

http://msdn.microsoft.com/en-us/library/system.net.ipaddress.any.aspx



回答6:

The MSDN library does seem contradcitory regarding IPAddress.Any. The Bind doc

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind.aspx

says that the 'most suitable' address is chosen, but the IPAddress.Any doc

http://msdn.microsoft.com/en-us/library/system.net.ipaddress.any.aspx

says that with this constant the socket must listen for activity on all interfaces.

However, I'm told that it's the IPAddress.Any doc that is correct.

(adding this as an answer since I don't have enough rep to leave comments).