在多宿主主机中选择接口
在 C 中通过套接字进行编程时,可以通过使用 getaddrinfo
函数自动获取有关其接口的信息,方法是使用节点为 NULL
和 AI_PASSIVE
的节点来调用该函数。 >hints.ai_flags 中的标志。它返回适合 bind()
ing 和 accept()
ing 连接的 addrinfo
结构列表。在配置了默认接口的多宿主主机上,getaddrinfo
将返回与默认接口相关的结构,但该结构可能不是正确的。如何调用 getaddrinfo 来从所有可用接口返回结构,以便可以适当地选择一个。
When programming through sockets in C, one can automatically get information about their interfaces through the getaddrinfo
function by invoking it with the node as NULL
and the AI_PASSIVE
flag in hints.ai_flags
. It returns a list of addrinfo
structures that will be suitable for bind()
ing and accept()
ing connections. On a multi-homed host with a default interface configured, getaddrinfo
will return structures pertaining to the default interface which might not be the right one. How can getaddrinfo
be invoked to return structures from all available interfaces so that the one can be chosen appropriately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您想将节点设置为 NULL。将其设置为您想要的接口的 IP 地址。
从
手册页:
有多种原因导致链表可能具有多个 addrinfo 结构,
包括:网络主机是多宿主的,可通过多种协议访问(例如,
AF_INET 和 AF_INET6);或者可以从多种套接字类型(例如,一个 SOCK_STREAM 地址和另一个 SOCK_DGRAM 地址)获得相同的服务。
使用 getifaddr 手动搜索所有接口。
Maybe you want to set node as NULL. Set it to the IP address of the interface you want.
to
From the man page:
There are several reasons why the linked list may have more than one addrinfo structure,
including: the network host is multihomed, accessible over multiple protocols (e.g. both
AF_INET and AF_INET6); or the same service is available from multiple socket types (one SOCK_STREAM address and another SOCK_DGRAM address, for example).
Use getifaddr to search through all interfaces manually.