Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

sockets

bind

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?

like image 845
Ben S Avatar asked Sep 05 '25 11:09

Ben S


1 Answers

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

like image 57
Brian Agnew Avatar answered Sep 08 '25 18:09

Brian Agnew