如何将套接字动态绑定到一个网络接口?
目前,我执行以下操作来侦听所有接口上的任何可用端口:
// hints struct for the getaddrinfo call
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// Fill in addrinfo with getaddrinfo
if (getaddrinfo(NULL, "0", &hints, &res) != 0) {
cerr << "Couldn't getaddrinfo." << endl;
exit(-1);
}
我想动态绑定到仅一个接口,即系统的非环回接口。
我该怎么做呢?
Currently I do the following to listen on any available port on all interfaces:
// hints struct for the getaddrinfo call
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// Fill in addrinfo with getaddrinfo
if (getaddrinfo(NULL, "0", &hints, &res) != 0) {
cerr << "Couldn't getaddrinfo." << endl;
exit(-1);
}
I would like to dynamically bind to only one interface, the non-loopback interface of the system.
How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看一下 SO_BINDTODEVICE。 Tuxology对此有一个很好的描述
Take a look at SO_BINDTODEVICE. Tuxology has a good description of this
如果您想要一本有关此问题的优秀书籍:
W. Richard Stevens 所著的《UNIX 网络编程》,共两卷。 第一卷介绍了套接字。
还有《UNIX 环境中的高级编程》,同样由 Stevens 编写,由 Rago 更新为第三版。
这些被广泛认为是 UNIX / Linux / 等的经典和标准参考
If you want an excellent book on the matter:
UNIX Network Programming by W. Richard Stevens, in two volumes. Volume one covers sockets.
Also Advanced Programming in the UNIX Environment, also by Stevens and updated in 3rd edition by Rago.
These are widely considered to be classics and standard references for UNIX / Linux / et al
您可以使用 SIOCGIFADDR
ioctl()
确定特定接口的 IP 地址,然后bind()
到该地址。You can use the SIOCGIFADDR
ioctl()
to determine the IP address of a specific interface, and thenbind()
to that address.