Matthieu N.
Matthieu N.

Reputation:

Binding to a specific NIC in a posix manner

I have 3 network interfaces on my machine (eth0-2) each one has its own network subnet 192.168.10.,192.168.20.,192.168.30.. I was wondering how does one using BSD sockets listen on a port for a specific NIC, For example listen on port 10000 for eth1 (192.168.20.), At the moment I've got that seems to list/bind to eth0 only. The OS I'm currently using is Ubuntu, but I would like the solution to work/portable on any posix system.

On a side note I'm developing my application in C++, and would appreciate some guidance on networking libraries in C++, I've had a look at Qt however the license is not suitable for the type of development I'm doing.

Upvotes: 0

Views: 694

Answers (2)

Gene Goykhman
Gene Goykhman

Reputation: 2001

If you BIND a single listening socket to all the IPs on the host (on port 10000, for example), I do not believe there is a general mechanism to determine the IP address on which a particular ACCEPT-ed connection came in.

One solution is to BIND a separate socket to each of your 3 IP addresses, and then use SELECT to watch for incoming connections. That way you'll always know which incoming IP address was used.

As an alternative, if you have full control over the client-side protocol, you could design in a requirement that the client transmits the target IP that was used immediately after establishing a socket connection. That would allow you to use a single server socket to listen for all incoming connections, but would require you to trust the information that the client was providing.

Upvotes: 0

janm
janm

Reputation: 18359

The bind() system call lets you specify the address to bind the socket to. You can bind to a specific address, or you can bind to INADDR_ANY, which will listen on all incoming addresses, regardless of interface.

As for network libraries, boost::asio is good. Of course, you might want to specify more requirements than "a networking library" to get a better recommendation.

Upvotes: 2

Related Questions