unpack_sockaddr_in#

Split a packed sockaddr_in back into its port and 4-byte address.

Synopsis#

my ($port, $packed_ipv4) = unpack_sockaddr_in($sockaddr);

What you get back#

A two-element list: the port as an integer, the address as a 4-byte packed string. Feed the second through inet_ntoa to see it as dotted-quad. In scalar context only the address comes back.

Examples#

my $peer = getpeername($sock);
my ($port, $ip) = unpack_sockaddr_in($peer);
printf "connected from %s:%d\n", inet_ntoa($ip), $port;

Edge cases#

  • Input that is not exactly a sockaddr_in croaks “Bad arg length”; undef croaks “Undefined address”.

  • A family other than AF_INET croaks “Bad address family”.

See also#

  • pack_sockaddr_in - reverse direction.

  • sockaddr_family - read just the family byte without unpacking.

  • unpack_sockaddr_in6 - IPv6 counterpart.

  • inet_ntoa - turn the returned packed address into a string.