how to bind raw socket to specific interface

const char *opt;
opt = "eth0";
const len = strnlen(opt, IFNAMSIZ);
if (len == IFNAMSIZ) {
    fprintf(stderr, "Too long iface name");
    return 1;
}
setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, opt, len);

First line: set up your variable

Second line: tell the program which interface to bind to

Lines 3-5: get length of interface name and check if it’s size not too big.

Six line: set the socket options for socket sd, binding to the device opt.

setsockopt prototype:

int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen);

Also, make sure you include the if.h, socket.h and string.h header files

Leave a Comment