Reputation: 1520
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?
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;
};
Upvotes: 3
Views: 4177
Reputation: 46323
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);
Upvotes: 3
Reputation: 215193
res
is a pointer to the place where you want the results (which are themselves in the form of a pointer) stored. Thus you do something like:
struct addrinfo hints = { .ai_socktype = SOCK_STREAM };
struct addrinfo *ai;
int err_code = getaddrinfo(hostname, service, &hints, &ai));
Afterwards, if there was no error, ai
has been updated to point at your results (the first element of a linked list of addrinfo
structures).
Upvotes: 2