Is it possible to bind a udp socket to a specific interface so it sends data through that interface? I have an application that uses several Udp Sockets to send data and it is running on a machine with several interfaces. I know it's possible to do this by specifying the interface name by using this code:
int UdpSocket::open(const char *interface)
{
send_fd_ = ::socket(AF_INET, SOCK_DGRAM, 0);
if (send_fd_ < 0)
{
perror("socket");
return -1;
}
int val = 1;
int rc = ::setsockopt(send_fd_, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
if (rc < 0)
{
perror("sesockopt");
close();
return -1;
}
unsigned char ttl = 16;
rc = ::setsockopt(send_fd_, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
if (rc < 0)
{
perror("sesockopt_ttl");
close();
return -1;
}
if (interface != NULL)
{
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), interface);
rc = ::setsockopt(send_fd_, SOL_SOCKET, SO_BINDTODEVICE, (void*)&ifr, sizeof(ifr));
if (rc < 0)
{
perror("sesockopt");
close();
return -1;
}
}
const int flags = ::fcntl(send_fd_, F_GETFL, 0);
::fcntl(send_fd_, F_SETFL, flags | O_NONBLOCK);
return 0;
}
But this requires that the app is run with root privileges, otherwise it it will throw an error saying the "operation not permitted."