gpt4 book ai didi

c++ - 如何在 linux 中指定用于套接字的接口(interface)

转载 作者:太空狗 更新时间:2023-10-29 11:46:16 26 4
gpt4 key购买 nike

是否可以将 udp 套接字绑定(bind)到特定接口(interface),以便它通过该接口(interface)发送数据?我有一个使用多个 Udp 套接字发送数据的应用程序,它在具有多个接口(interface)的机器上运行。我知道可以通过使用以下代码指定接口(interface)名称来做到这一点:

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;
}

但这需要应用程序以 root 权限运行,否则它会抛出一个错误,指出“不允许操作”。

最佳答案

最简单也是迄今为止最明智的方法是添加 route (s) 匹配您的多播目的地:

~# route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0

由于操作系统网络栈根据路由表为多播数据包选择出站接口(interface)。这也适用于监听——你只需绑定(bind)到组地址,内核就会为你选择正确的接口(interface)。您仍然需要像往常一样加入群组。

关于c++ - 如何在 linux 中指定用于套接字的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12371385/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com