解释 getaddrinfo( ) 的参数

Explain parameters of getaddrinfo( )

我不明白的是**res双指针,在手册页中它指出:

The hints argument points to an addrinfo structure that specifies criteria for selecting the socket address structures returned in the list pointed to by res.

我看到 *hints 是指向 addrinfo 结构的指针,但是 **res 是如何返回套接字地址结构的?

Specification:

int getaddrinfo(const char *node, const char *service,
                const struct addrinfo *hints,
                struct addrinfo **res);


struct addrinfo {
    int              ai_flags;
    int              ai_family;
    int              ai_socktype;
    int              ai_protocol;
    socklen_t        ai_addrlen;
    struct sockaddr *ai_addr;
    char            *ai_canonname;
    struct addrinfo *ai_next;
};

res 是指向您希望存储结果(它们本身以指针的形式)的位置的指针。因此,您可以执行以下操作:

struct addrinfo hints = { .ai_socktype = SOCK_STREAM };
struct addrinfo *ai;
int err_code = getaddrinfo(hostname, service, &hints, &ai));

之后,如果没有错误,ai 已更新为指向您的结果(addrinfo 结构链表的第一个元素)。

指向指针的指针的使用是一种常见模式,其中函数使用 "out" 参数来 return 已分配内存的地址。这样做是为了让调用者不必预先分配,有时大小未知。

它的典型用法是通过地址运算符 (&),您可以在其中使用如下指针类型:

struct addrinfo *result;
getaddrinfo("foo", "baz", NULL, &result);

然后,result,这是一个未初始化的变量 指向一个真正的内存地址,在后面的代码中,预计它将被释放来电者:

freeaddrinfo(result);