I am setting the socket option SO_BINDTODEVICE
for eth0 to be able to route the packets only through that interface. However, bind()
fails with " Port already in use
" error with this option when the server is restarted despite having the socket option SO_REUSEADDR
.
Here is my code snippet:
int listenFd;
int temp;
int buf_size = 0;
struct sockaddr_in sAddr;
int enable = 1;
struct ifreq ifr;
/* setup listening socket */
listenFd = socket(AF_INET, SOCK_STREAM, 0);
if (setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
{
close (listenFd);
return -1;
}
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth0");
ioctl(listenFd, SIOCGIFINDEX, &ifr);
if (setsockopt(listenFd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, IFNAMSIZ) < 0)
{
close (listenFd);
return -1;
}
/* Initialize the server address and bind to the required port */
memset(&sAddr, 0, sizeof (struct sockaddr_in));
sAddr.sin_family = AF_INET;
sAddr.sin_addr.s_addr = htonl(INADDR_ANY);
sAddr.sin_port = 8080;
/* bind to the socket, */
temp = bind(listenFd, (struct sockaddr*) &sAddr, sizeof (sAddr));
if (temp < 0)
{
close (listenFd);
return -1;
}
/* Set socket options to max buffer size */
buf_size = REST_MAX_HTTP_BUFFER_LENGTH;
temp = setsockopt(listenFd, SOL_SOCKET, SO_RCVBUF, &buf_size, sizeof(buf_size));
if (temp < 0)
{
close (listenFd);
return -1;
}
Is anything missing in the code above? I have tried the other way of getting IP address of the interface (eth0) and assigning it to sAddr.sin_addr.s_addr but that did not work.
Hope to get some details. Thanks in advance!!