Ben S
Ben S

Reputation: 69342

How do I dynamically bind a socket to only one network interface?

Currently I do the following to listen on any available port on all interfaces:

// hints struct for the getaddrinfo call
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;

// Fill in addrinfo with getaddrinfo
if (getaddrinfo(NULL, "0", &hints, &res) != 0) {
    cerr << "Couldn't getaddrinfo." << endl;
    exit(-1);
}

I would like to dynamically bind to only one interface, the non-loopback interface of the system.

How would I go about doing this?

Upvotes: 4

Views: 2808

Answers (3)

Beano
Beano

Reputation: 7841

You can use the SIOCGIFADDR ioctl() to determine the IP address of a specific interface, and then bind() to that address.

Upvotes: 1

hoohoo
hoohoo

Reputation:

If you want an excellent book on the matter:

UNIX Network Programming by W. Richard Stevens, in two volumes. Volume one covers sockets.

Also Advanced Programming in the UNIX Environment, also by Stevens and updated in 3rd edition by Rago.

These are widely considered to be classics and standard references for UNIX / Linux / et al

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272277

Take a look at SO_BINDTODEVICE. Tuxology has a good description of this

Upvotes: 5

Related Questions