Dima Dima - 2 months ago 7
Linux Question

how to bind raw socket to specific interface

My application is running on CentOS 5.5.
I'm using raw socket to send data:

sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (sd < 0) {
// Error
}
const int opt_on = 1;
rc = setsockopt(m_SocketDescriptor, IPPROTO_IP, IP_HDRINCL, &opt_on, sizeof(opt_on));
if (rc < 0) {
close(sd);
// Error
}
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = my_ip_address;

if (sendto(m_SocketDescriptor, DataBuffer, (size_t)TotalSize, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0) {
close(sd);
// Error
}


How can I bind this socket to specific network interface (say eth1)?

Answer
char *opt;
opt = "eth0";
setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, opt, 4);

First line: set up your variable

Second line: tell the program which interface to bind to

Third line: set the socket options for socket sd, binding to the device opt, and since opt is four characters long set 4 as the length.

setsockopt prototype:

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

Also, make sure you include the socket.h header file