bind socket to network interface

You can bind to a specific interface by setting SO_BINDTODEVICE socket option.

struct ifreq ifr;

memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth0");
if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
    ... error handling ...
}

Warning: You have to be root and have the CAP_NET_RAW capability in order to use this option.

The second method is that you can resolv IP address tied to an interface with getifaddrs().

Follow the latter link for a comprehensive example.


The only way you can do it is as you mention -

by setting the particular IP address using serv_addr.sin_addr.s_addr

You can't do it without knowing the address to bind to.

You can use ioctls to determine the current IP address if you need, though there may be a cleverer way to do this these days - I've not done much in modern Linux distros lately.