Lesson 5 of 18 The System Calls

getaddrinfo(): Resolving Addresses

Use getaddrinfo() to turn host names and ports into socket addresses for IPv4 and IPv6, with hints, AI_PASSIVE, gai_strerror and getnameinfo.

40-50 min beginner 0/18 lessons done
Course contents Lesson 5 of 18 · 0 done
On this page (12 sections)
  1. What you will learn
  2. The signature
  3. Hints
  4. Client use: “where do I connect?”
  5. Server use: “where do I listen?”
  6. A complete lookup tool
  7. The reverse: getnameinfo()
  8. Retire gethostbyname() and gethostbyaddr()
  9. Checklist: making IPv4 code IP-agnostic
  10. Key takeaways
  11. Exercises
  12. Quiz

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 what AI_PASSIVE does for servers.
  • How to free results and report errors.
  • The reverse direction with getnameinfo(), and the old gethostbyname() 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:

FieldCommon valuesEffect
ai_familyAF_UNSPEC, AF_INET, AF_INET6Which address families to return. AF_UNSPEC returns both.
ai_socktypeSOCK_STREAM, SOCK_DGRAMWithout it you get one entry per socket type for each address.
ai_flagsAI_PASSIVEWith node == NULL, return the wildcard address for bind().
AI_NUMERICHOSTTreat node as a literal address; never do a DNS lookup.
AI_CANONNAMEFill ai_canonname in the first result.
AI_ADDRCONFIGOnly 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_socktype so each address appears once rather than once per socket type.
  • The cast pattern from lesson 4 picks sin_addr or sin6_addr before calling inet_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_errno variable.
  • 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:

  1. gethostbyname() / hand-filled sockaddr_in → getaddrinfo() with AF_UNSPEC, then use ai_family, ai_addr, ai_addrlen.
  2. struct sockaddr_in used to receive a peer address → struct sockaddr_storage.
  3. sizeof(struct sockaddr_in) passed as a length → the ai_addrlen or socklen_t returned by the call.
  4. INADDR_ANY → AI_PASSIVE with a NULL node (or in6addr_any).
  5. INADDR_LOOPBACK → in6addr_loopback, or getaddrinfo() without AI_PASSIVE.
  6. inet_aton() / inet_addr() → inet_pton().
  7. inet_ntoa() → inet_ntop() or getnameinfo().
  8. gethostbyaddr() → getnameinfo().
  9. Fixed char buf[16] for addresses → INET6_ADDRSTRLEN or NI_MAXHOST.
  10. 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 as AI_PASSIVE for servers.
  • Errors come back as EAI_* codes; print them with gai_strerror(). Always freeaddrinfo().
  • Use getnameinfo() for the reverse direction; drop gethostbyname() and inet_ntoa().

Exercises

  1. Extend lookup.c to print the canonical name (set AI_CANONNAME) and the port when a service argument is given.
  2. Change ai_socktype to 0 and rerun. Explain why each address now appears several times.
  3. Write reverse.c that takes an IP address as text and prints its host name using getnameinfo() with NI_NAMEREQD.

Quiz

  1. What does getaddrinfo(NULL, "8080", &hints, &res) return with and without AI_PASSIVE?
  2. How do you get a readable message when getaddrinfo() fails?
  3. Why should a busy server log peers with NI_NUMERICHOST?
Show answers
  1. 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).
  2. Pass its return value to gai_strerror(). It does not set errno for most errors.
  3. 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.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).