getaddrinfo#

Resolve a host name and/or service name into a list of ready-to-use address records, honouring IPv4/IPv6 and protocol preferences carried through a hints hash.

Synopsis#

my ($err, @res) = getaddrinfo($host, $service);
my ($err, @res) = getaddrinfo($host, $service, { family => AF_INET6 });

What you get back#

A list whose first element is an error string — empty on success, otherwise a human-readable message from gai_strerror. Every subsequent element is a hash reference describing one resolved endpoint, with keys:

  • family — integer address family (AF_INET, AF_INET6, …).

  • socktype — integer socket type (SOCK_STREAM, SOCK_DGRAM, …).

  • protocol — integer protocol number.

  • addr — packed sockaddr ready for bind or connect.

  • canonname — canonical hostname (only populated when the hints hash requests it with flags => AI_CANONNAME).

The hints hash accepts family, socktype, protocol, and flags, each an integer; unknown keys are ignored.

Examples#

my ($err, @res) = getaddrinfo("example.com", "https",
    { socktype => SOCK_STREAM });
die "resolve: $err\n" if $err;
for my $r (@res) {
    socket(my $s, $r->{family}, $r->{socktype}, $r->{protocol}) or next;
    connect($s, $r->{addr}) and last;
    close $s;
}
## Numeric-only, no DNS lookup, no service lookup.

my ($err, @res) = getaddrinfo("2001:db8::1", "443",
    { flags => AI_NUMERICHOST | AI_NUMERICSERV });
## Listening side: ask for a wildcard bind address.

my ($err, @res) = getaddrinfo(undef, "8080",
    { flags => AI_PASSIVE, family => AF_INET6 });

Edge cases#

  • On error the result list is exactly one element — the message — so scalar @res is 1 and the first hashref is absent.

  • Pass undef for $host to resolve a service with no specific host (typically combined with AI_PASSIVE).

  • Pass undef for $service to resolve a host with no port.

Differences from upstream#

Fully compatible with upstream Socket.

See also#

  • getnameinfo — reverse direction, sockaddr to host and service.

  • inet_pton — parse a single address string without a full resolver.

  • pack_sockaddr_in, pack_sockaddr_in6 — when you already have the address bytes and just need the struct.