Search code examples
csocketswebsocketwebservergetaddrinfo

Explain parameters of getaddrinfo( )


What I don't understand is the **res double pointer, in the man page it states:

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.

I see that *hints is a pointer to the addrinfo struct but how is **res returning the socket address structures?

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;
};

Solution

  • The usage of a pointer to pointer is a common pattern where the function uses an "out" parameter to return the address of allocated memory. This is done so that the caller doesn't have to preallocate, sometimes an unknown size.

    The typical usage of this is via the address operator (&) where you use a pointer type like this:

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

    Then, result, which was an uninitialized variable is pointing to a real memory address, and later in the code it is expected it will be freed by the caller:

    freeaddrinfo(result);