Вопрос

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.

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top