Resolve Hostnames in C with getaddrinfo
Resolve hostnames in C with getaddrinfo, walk the result list, connect to the first address that works, and free it with freeaddrinfo on Linux.

Programs rarely connect to a literal address. Users type names such as example.com, and a name may map to several IPv4 and IPv6 addresses. The function that turns a name and a service into a list of ready-to-use socket addresses is getaddrinfo. This post shows how to call it, how to read the list it returns, how to try each address in turn, and how to avoid the mistakes that leak memory or hard-code IPv4. Examples target Linux 6.12 with glibc 2.40.
The function is specified in POSIX.1-2024 and described in the getaddrinfo(3) man page.
Why not gethostbyname
Older code uses gethostbyname. It returns only IPv4 addresses, uses a static buffer that is not thread-safe, and has no way to say which socket type you want. POSIX marks it obsolete. getaddrinfo replaces it: it handles IPv4 and IPv6, it is thread-safe, and it returns structures you can pass straight to socket and connect. New code should never call gethostbyname.
The function and its arguments
int getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res);nodeis a hostname or a numeric address string.NULLmeans "no host", used for servers.serviceis a port number as text, such as"80", or a service name such as"http"that is looked up in the services database.hintsnarrows the search. You set only the fields you care about and zero the rest.resreceives a pointer to the head of a linked list ofstruct addrinfo.
It returns 0 on success. On failure it returns a nonzero error code, which is not errno. Turn it into text with gai_strerror, not perror.
The hints structure
Always zero the hints first, then set what you need:
| Field | Typical value | Effect |
|---|---|---|
ai_family | AF_UNSPEC | Accept both IPv4 and IPv6; use AF_INET or AF_INET6 to restrict |
ai_socktype | SOCK_STREAM | Only return addresses for TCP; without it you get one entry per socket type |
ai_flags | AI_PASSIVE | For servers, with node NULL, return the wildcard address |
ai_flags | AI_NUMERICHOST | Refuse to do DNS; only parse numeric addresses |
ai_flags | AI_ADDRCONFIG | Return IPv6 only if this machine has an IPv6 address configured |
Leaving ai_socktype as zero is a common cause of confusing output, because the same address then appears once for SOCK_STREAM, once for SOCK_DGRAM and once for SOCK_RAW.
Walking the result list
The result is a linked list through ai_next. Each node holds everything socket and connect need: ai_family, ai_socktype, ai_protocol, ai_addr and ai_addrlen. The list has more than one entry when the name has several addresses, and the system sorts it by the rules of RFC 6724. A robust client tries each entry until one connects. When you have finished, release the whole list with a single freeaddrinfo call on the head.
A client that resolves and connects
#define _DEFAULT_SOURCE
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
static int connect_to(const char *host, const char *port)
{
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo *res;
int rc = getaddrinfo(host, port, &hints, &res);
if (rc != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
return -1;
}
int fd = -1;
for (struct addrinfo *ai = res; ai != NULL; ai = ai->ai_next) {
char text[INET6_ADDRSTRLEN];
void *src = ai->ai_family == AF_INET
? (void *)&((struct sockaddr_in *)ai->ai_addr)->sin_addr
: (void *)&((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
inet_ntop(ai->ai_family, src, text, sizeof text);
printf("trying %s\n", text);
fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (fd < 0)
continue;
if (connect(fd, ai->ai_addr, ai->ai_addrlen) == 0)
break;
close(fd);
fd = -1;
}
freeaddrinfo(res);
return fd;
}
int main(void)
{
int fd = connect_to("localhost", "7070");
if (fd < 0) {
fprintf(stderr, "could not connect\n");
return EXIT_FAILURE;
}
printf("connected\n");
close(fd);
return EXIT_SUCCESS;
}Compile with gcc -std=c11 -Wall -Wextra -o resolve_connect resolve_connect.c. On a machine where localhost maps to both ::1 and 127.0.0.1, and the echo server from an earlier post listens only on IPv4, the output is:
trying ::1
trying 127.0.0.1
connectedThe first attempt fails with ECONNREFUSED because nothing listens on the IPv6 loopback, the code closes that socket and moves on to the next entry. The order depends on the system's address sorting and on /etc/hosts, so your machine may try 127.0.0.1 first.
Using it for a server
A server passes NULL as the node and sets AI_PASSIVE, so the result is a wildcard address ready for bind. With AF_INET6 and the right socket option you get a dual-stack listener, which a later post covers. The port in service is converted to network byte order for you, which removes the htons step.
Error handling
getaddrinfo reports its own codes. EAI_NONAME means the name or service is unknown, EAI_AGAIN is a temporary failure in name resolution worth retrying, EAI_FAMILY means the family is not supported, and EAI_SYSTEM means a system error occurred and errno holds the detail. Print them with gai_strerror.
Blocking and timeouts
The call is blocking and may talk to a DNS server, so it can take seconds. There is no timeout argument. If a stalled lookup must not freeze your program, run it in a separate thread, or use glibc's asynchronous getaddrinfo_a, or a dedicated resolver library. Do not call it from a signal handler or hold a lock around it.
Common mistakes
Forgetting
freeaddrinfo, which leaks the list on every call.Reading
ai_nextafter freeing the list.Using only the first result, so a name with a dead IPv6 address fails when IPv4 would have worked.
Printing
errnoinstead ofgai_strerror, which shows an unrelated message.Hard-coding
AF_INETand silently dropping IPv6 users.
Where the answers come from
getaddrinfo is not a DNS client. It asks the system's name service switch, configured in /etc/nsswitch.conf, which decides the order of sources. On a typical Linux machine the first source is the local file /etc/hosts, and the next is DNS through the servers listed in /etc/resolv.conf. That is why localhost resolves without any network, and why changing a line in /etc/hosts changes what your program connects to. When a lookup behaves differently in your program than in a browser, the cause is often that the two use different resolvers.
Names can map to several addresses for good reasons: a service may have both an IPv4 and an IPv6 address, or a provider may publish several servers under one name to spread the load. Trying each entry in order is the simplest correct client. Modern clients go further and race the families against each other, an approach standardised as Happy Eyeballs in RFC 8305, so a broken IPv6 path costs a fraction of a second and not a full timeout. You do not need that for a first program, but you should know why a naive loop can feel slow on a network with half-working IPv6.
Numeric hosts and service names
The same function parses numeric addresses, so one code path serves both "192.0.2.10" and "example.com". Add AI_NUMERICHOST to the flags when the input must be an address and a DNS query would be a bug, for example when validating configuration. Likewise, AI_NUMERICSERV says the service is a port number and must not be looked up by name. Using these flags avoids a surprise delay when a malformed value would otherwise trigger a network lookup.
Going back from an address to a name
The reverse direction is getnameinfo. Given a sockaddr and its length, it fills buffers with a host and service string, and with NI_NUMERICHOST | NI_NUMERICSERV it never queries DNS. Prefer it over the inet_ntop plus cast pattern in the example when you want one call that works for both families. Reverse DNS names are not proof of identity, because whoever controls the address range controls its reverse records, so log them but never base access control on them.

