Choosing the interface in multi-homed hosts

混江龙づ霸主 提交于 2019-12-07 13:06:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7492269/choosing-the-interface-in-multi-homed-hosts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!