```{index} single: getaddrinfo (Socket) ``` ```{index} single: Socket::getaddrinfo ``` # 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 ```perl 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 the error, a dualvar: as a string it is empty on success, otherwise the message from `gai_strerror`; as a number it is 0 or the `EAI_*` code, so `$err == EAI_NONAME` works. 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 ```perl 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; } ``` ```perl # Numeric-only, no DNS lookup, no service lookup. my ($err, @res) = getaddrinfo("2001:db8::1", "443", { flags => AI_NUMERICHOST | AI_NUMERICSERV }); ``` ```perl # 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. - Hints that are defined but not a hash reference croak "hints is not a HASH reference". ## 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.