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

I am currently performing the following steps 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 communicate with only one interface, without a loopback system interface.

How can I do it?

+3
source share
3 answers

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

+4
source

If you want a great book on this subject:

UNIX Networking by W. Richard Stevens in two volumes. The first volume covers sockets.

UNIX, 3- Rago.

UNIX/Linux/et al.

+1

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

+1
source

Source: https://habr.com/ru/post/1712459/


All Articles