views:

820

answers:

3

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.

+2  A: 

Yes, IPAddress.Any will listen on all interfaces.

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

JonMR
Ok, that helps (the Bind method just says that framework picks the address to listen on, which is pretty vague). But what about if I only want to listen on 5 of 10 IP addresses assigned to the computer? Do I need 5 sockets for that? or can I call Bind() multiple times with different endpoints?
Mystere Man
Yes, you one per address, unless you bind to Any or IPv6Any.
Lex Li
+3  A: 

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.

Bevan
Yes, I'm aware that you assign IP addresses to interfaces, but .NET hides that from you and you simply bind to endpoints. I'm a bit confused why you can listen on mulitple interfaces with IPAddress.Any but need multiple sockets to listen to specific ones.
Mystere Man
I suspect it's a case of "let's make the common case easy to achieve" by the designers of the framework, providing a useful shortcut.
Bevan
Any and IPv6Any can be considered as shortcuts. But you could not ask a framework to provide you all shortcuts you want. I totally agree with Bevan. When you play more with frameworks and you start to design your own, you will see it is always hard to make choices.
Lex Li
+1  A: 

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.

Matt Davis
Ok, thanks for the definitive answer.
Mystere Man
No, IPAddress.Any does not bind the Socket objects to all IP addresses if you simply count IP v6 addresses.The correct way is to create two Socket objects. Then one binds to IPAddress.Any, and the other binds to IPAddress.IPv6Any.
Lex Li
Good point. My project is still solely IPv4, so IPv6 was not even a consideration when I wrote my answer.
Matt Davis