在多宿主主机中选择接口

发布于 2024-12-05 11:59:53 字数 354 浏览 4 评论 0原文

在 C 中通过套接字进行编程时,可以通过使用 getaddrinfo 函数自动获取有关其接口的信息,方法是使用节点为 NULLAI_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱纠缠 2024-12-12 11:59:53

也许您想将节点设置为 NULL。将其设置为您想要的接口的 IP 地址。

socket_result = getaddrinfo(NULL, port_num_string, &hints, &sock_addr_list);

socket_result = getaddrinfo("192.168.1.10", port_num_string, &hints, &sock_addr_list);

手册页:

有多种原因导致链表可能具有多个 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.

socket_result = getaddrinfo(NULL, port_num_string, &hints, &sock_addr_list);

to

socket_result = getaddrinfo("192.168.1.10", port_num_string, &hints, &sock_addr_list);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文