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. When the input is shorter than a sockaddr_in, both elements come back as undef.

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 shorter than sockaddr_in yields (undef, undef) rather than croaking — check the first return value before using it.

  • The address family byte in the input is not validated; the caller is expected to have an IPv4 sockaddr in hand.

Differences from upstream#

Fully compatible with upstream Socket.

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.