Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a socket to multiple interfaces

After hours of searching on the internet, I still wasn't able to find an answer for my problem.

My task is to create a server that accepts sockets from a variable number of interfaces (given in a config file as eth0, eth1, etc.).

What is the easiest way to do this? Is there any way to bind one socket to multiple interfaces? I haven't found a way to do that yet.
Or, do I have to use INADDR_ANY and somehow find out the interface which the packet was sent from?

Is there another way to handle this problem?

like image 768
Hynek Blaha Avatar asked Oct 03 '12 13:10

Hynek Blaha


People also ask

Can you bind a socket to multiple ports?

Is it possible to bind one process to multiple ports? Yes. Yes, each listening (bound) port is serviced by a separate socket (as are all the connections made from each listening port).

How do you bind a socket?

To bind a socketCall the bind function, passing the created socket and sockaddr structure returned from the getaddrinfo function as parameters. Check for general errors. Once the bind function is called, the address information returned by the getaddrinfo function is no longer needed.

Can you bind and connect the same socket?

Yes, you can.

What is the use bind () socket call?

The bind() function binds a unique local name to the socket with descriptor socket. After calling socket(), a descriptor does not have a name associated with it. However, it does belong to a particular address family as specified when socket() is called. The exact format of a name depends on the address family.


1 Answers

You either bind(2) one socket to all interfaces with INADDR_ANY, or create multiple sockets and bind each to IP address of the desired interface. In any case, set SO_REUSEADDR option on the sockets.

like image 158
Nikolai Fetissov Avatar answered Oct 08 '22 14:10

Nikolai Fetissov