28

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?

Amelia
  • 2,967
  • 2
  • 24
  • 39
Hynek Blaha
  • 633
  • 2
  • 6
  • 8

1 Answers1

39

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.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • @NikolaiNFetissov Am I able to accept more than 65K connection limit when I use INADDR_ANY or I have to bind each IP separately for that? – Etherealone Jul 11 '13 at 20:17
  • 5
    @Tolga, you are probably referring to the fact that TCP port number is a 16-bit integer. That is not a limiting factor here since each given TCP connection is a 4-tuple of (src addr, src port, dest addr, dest port). You are much more likely to hit the per-process file descriptor limit on your server before reaching 65536 connections. – Nikolai Fetissov Jul 12 '13 at 13:34
  • @NikolaiFetissov Thanks for this clear Answer. Presumably, the second option of using multiple sockets involves more programming effort, as we need to listen to and check for connections on multiple sockets (using `select` in C, perhaps). The first option seems transparent to the application so looks to me to be easier to program. Would you agree? In what circumstances would we opt for the second option? – flow2k Jun 28 '19 at 08:10
  • In a case where you need different behavior on different networks you host is connected to, like a proxy or something like that. – Nikolai Fetissov Jun 28 '19 at 11:33