Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen on multiple IP addresses?

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.

like image 496
Erik Funkenbusch Avatar asked Nov 22 '09 02:11

Erik Funkenbusch


2 Answers

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.

like image 131
Matt Davis Avatar answered Sep 19 '22 13:09

Matt Davis


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.

like image 22
Bevan Avatar answered Sep 21 '22 13:09

Bevan