pack_sockaddr_in#

Build a packed sockaddr_in from a port number and a 4-byte IPv4 address, ready to hand to bind or connect.

Synopsis#

my $sin = pack_sockaddr_in($port, $packed_ipv4);

What you get back#

A fixed-size byte string whose layout matches the platform’s struct sockaddr_in: address family (AF_INET), port in network byte order, the raw 4 address bytes, and trailing padding. The result is opaque from Perl’s perspective - treat it as a cookie for the socket built-ins.

Examples#

my $addr = pack_sockaddr_in(80, inet_aton("example.com"));
connect($sock, $addr) or die $!;
# Bind to every local interface on a chosen port.
bind($sock, pack_sockaddr_in(8080, INADDR_ANY)) or die $!;

Edge cases#

  • Port is truncated to 16 bits; a value above 65535 warns “Port number above 0xFFFF, will be truncated to N”. An undef port is 0.

  • An address of any length but 4 croaks “Bad arg length”; an undef address croaks “Undefined address”.

  • The address argument is a packed 4-byte string, not a dotted-quad literal. Pass inet_aton(...) or INADDR_*.

See also#

  • unpack_sockaddr_in - reverse direction.

  • sockaddr_in - dual-mode shortcut: packs in scalar context, unpacks in list context (a Perl sub in Socket.pm).

  • pack_sockaddr_in6 - IPv6 counterpart.

  • inet_aton - usual source of the address argument.