What you will learn
- How
getaddrinfo()resolves names (via DNS or/etc/hosts) and service names into ready-to-use addresses. - What to put in
hints, and whatAI_PASSIVEdoes for servers. - How to free results and report errors.
- The reverse direction with
getnameinfo(), and the oldgethostbyname()you should retire. - A checklist for converting IPv4-only code to IP-agnostic code.
The signature
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int getaddrinfo(const char *node, /* "example.com", "10.0.0.5" or NULL */
const char *service, /* "443", "https" or NULL */
const struct addrinfo *hints, /* what kind of results you want */
struct addrinfo **res); /* out: linked list of results */
void freeaddrinfo(struct addrinfo *res);
const char *gai_strerror(int errcode);
It returns 0 on success. On failure it returns an EAI_* code (not -1 and not via errno), which gai_strerror() turns into text.
Hints
Zero the whole hints struct, then set only what you care about:
| Field | Common values | Effect |
|---|---|---|
ai_family | AF_UNSPEC, AF_INET, AF_INET6 | Which address families to return. AF_UNSPEC returns both. |
ai_socktype | SOCK_STREAM, SOCK_DGRAM | Without it you get one entry per socket type for each address. |
ai_flags | AI_PASSIVE | With node == NULL, return the wildcard address for bind(). |
AI_NUMERICHOST | Treat node as a literal address; never do a DNS lookup. | |
AI_CANONNAME | Fill ai_canonname in the first result. | |
AI_ADDRCONFIG | Only return IPv6 results if this host has an IPv6 address (and same for IPv4). |
Client use: “where do I connect?”
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int rc = getaddrinfo("example.com", "443", &hints, &res);
if (rc != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
exit(1);
}
/* walk res->ai_next ... try each until connect() succeeds ... */
freeaddrinfo(res);
A name often resolves to several addresses (IPv6 and IPv4, or several servers). The robust pattern is to try each entry in order until one works. You’ll see that loop in every client in this course.
Server use: “where do I listen?”
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "5050", &hints, &res); /* wildcard address, port 5050 */
With AI_PASSIVE and a NULL node you get 0.0.0.0 and/or ::, meaning “accept connections on every interface”. Without AI_PASSIVE you’d get the loopback address instead, which only accepts connections from the same machine (sometimes exactly what you want for a development server).
A complete lookup tool
This program prints every address a name resolves to. Run it as ./lookup example.com.
/* lookup.c - print every address a host name resolves to */
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s hostname\n", argv[0]);
return 1;
}
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /* IPv4 or IPv6, we don't mind */
hints.ai_socktype = SOCK_STREAM; /* one entry per address, not per protocol */
struct addrinfo *results;
int rc = getaddrinfo(argv[1], NULL, &hints, &results);
if (rc != 0) {
fprintf(stderr, "lookup failed: %s\n", gai_strerror(rc));
return 2;
}
for (struct addrinfo *ai = results; ai != NULL; ai = ai->ai_next) {
char text[INET6_ADDRSTRLEN];
const void *raw;
const char *label;
if (ai->ai_family == AF_INET) {
const struct sockaddr_in *v4 = (const struct sockaddr_in *)ai->ai_addr;
raw = &v4->sin_addr;
label = "IPv4";
} else if (ai->ai_family == AF_INET6) {
const struct sockaddr_in6 *v6 = (const struct sockaddr_in6 *)ai->ai_addr;
raw = &v6->sin6_addr;
label = "IPv6";
} else {
continue;
}
inet_ntop(ai->ai_family, raw, text, sizeof text);
printf("%-4s %s\n", label, text);
}
freeaddrinfo(results);
return 0;
}
Sample output (addresses depend on your DNS):
$ ./lookup localhost
IPv6 ::1
IPv4 127.0.0.1
Things to notice:
- We set
ai_socktypeso each address appears once rather than once per socket type. - The cast pattern from lesson 4 picks
sin_addrorsin6_addrbefore callinginet_ntop(). freeaddrinfo()releases the whole list in one call. Don’t free individual nodes.
The reverse: getnameinfo()
getnameinfo() converts a socket address back into host and service strings, doing a reverse DNS lookup unless you ask for numeric output.
char host[NI_MAXHOST], serv[NI_MAXSERV];
int rc = getnameinfo((struct sockaddr *)&peer, peer_len,
host, sizeof host, serv, sizeof serv,
NI_NUMERICHOST | NI_NUMERICSERV);
if (rc == 0)
printf("peer is %s port %s\n", host, serv);
Use NI_NUMERICHOST in servers’ log lines: a reverse DNS lookup per connection is slow and can be spoofed. NI_NAMEREQD makes the call fail if no name exists. The servers in lesson 10 use exactly this to log who connected.
Retire gethostbyname() and gethostbyaddr()
Old code resolves names with gethostbyname(), which returns a struct hostent with an h_addr_list. Problems:
- IPv4 only in practice.
- Returns a pointer to static data, so it isn’t thread-safe.
- Errors go through a separate
h_errnovariable. - Marked obsolete in POSIX.
getaddrinfo() and getnameinfo() replace both. If you maintain code that uses them, the checklist below is the migration path.
Checklist: making IPv4 code IP-agnostic
When you port old code (or review new code), look for these and replace them:
gethostbyname()/ hand-filledsockaddr_in→getaddrinfo()withAF_UNSPEC, then useai_family,ai_addr,ai_addrlen.struct sockaddr_inused to receive a peer address →struct sockaddr_storage.sizeof(struct sockaddr_in)passed as a length → theai_addrlenorsocklen_treturned by the call.INADDR_ANY→AI_PASSIVEwith aNULLnode (orin6addr_any).INADDR_LOOPBACK→in6addr_loopback, orgetaddrinfo()withoutAI_PASSIVE.inet_aton()/inet_addr()→inet_pton().inet_ntoa()→inet_ntop()orgetnameinfo().gethostbyaddr()→getnameinfo().- Fixed
char buf[16]for addresses →INET6_ADDRSTRLENorNI_MAXHOST. - Broadcast → IPv6 has no broadcast; use multicast instead.
Key takeaways
getaddrinfo()turns names and ports into a list of fully prepared addresses for any IP version.- Zero
hints; set family, socket type and flags such asAI_PASSIVEfor servers. - Errors come back as
EAI_*codes; print them withgai_strerror(). Alwaysfreeaddrinfo(). - Use
getnameinfo()for the reverse direction; dropgethostbyname()andinet_ntoa().
Exercises
- Extend
lookup.cto print the canonical name (setAI_CANONNAME) and the port when a service argument is given. - Change
ai_socktypeto 0 and rerun. Explain why each address now appears several times. - Write
reverse.cthat takes an IP address as text and prints its host name usinggetnameinfo()withNI_NAMEREQD.
Quiz
- What does
getaddrinfo(NULL, "8080", &hints, &res)return with and withoutAI_PASSIVE? - How do you get a readable message when
getaddrinfo()fails? - Why should a busy server log peers with
NI_NUMERICHOST?
Show answers
- With
AI_PASSIVE: the wildcard addresses (0.0.0.0/::), for accepting on every interface. Without it: the loopback addresses (127.0.0.1/::1). - Pass its return value to
gai_strerror(). It does not seterrnofor most errors. - Reverse DNS lookups are slow (they can block for seconds), add load on DNS, and the returned names are controlled by whoever owns the peer’s address range.