Socket(3perl)
๐ NAME ๐
You're in Socket(3perl), bestie: Socket - networking constants and support functions. Low-level networking lore, no cap. ๐
โจ SYNOPSIS โจ
Socket is a low-level module used by, among other things, the IO::Socket family of modules. The following examples demonstrate some low-level uses, but a practical program would likely use the higher-level API provided by IO::Socket or similar instead.
use Socket qw(PF_INET SOCK_STREAM pack_sockaddr_in inet_aton);
socket(my $socket, PF_INET, SOCK_STREAM, 0)
or die "socket: $!";
my $port = getservbyname "echo", "tcp";
connect($socket, pack_sockaddr_in($port, inet_aton("localhost")))
or die "connect: $!";
print $socket "Hello, world!\n";
print <$socket>;
See also the "EXAMPLES" section. ๐ซถ
๐ DESCRIPTION ๐
This module provides a variety of constants, structure manipulators and other functions related to socket-based networking. The values and functions provided are useful when used in conjunction with Perl core functions such as socket(), setsockopt() and bind(). It also provides several other support functions, mostly for dealing with conversions of network addresses between human-readable and native binary forms, and for hostname resolver operations.
Some constants and functions are exported by default by this module; but for backward-compatibility any recently-added symbols are not exported by default and must be requested explicitly. When an import list is provided to the use Socket line, the default exports are not automatically imported. It is therefore best practice to always explicitly list all the symbols required. fr fr, just spell it out.
Also, some common socket "newline" constants are provided: the constants CR, LF, and CRLF, as well as $CR, $LF, and $CRLF, which map to "\015", "\012", and "\015\012". If you do not want to use the literal characters in your programs, then use the constants provided here. They are not exported by default, but can be imported individually, and with the :crlf export tag:
use Socket qw(:DEFAULT :crlf);
$sock->print("GET / HTTP/1.0$CRLF");
The entire getaddrinfo() subsystem can be exported using the tag :addrinfo; this exports the getaddrinfo() and getnameinfo() functions, and all the AI_*, NI_*, NIx_* and EAI_* constants. ๐ฆ
๐ฎ CONSTANTS ๐ฎ
In each of the following groups, there may be many more constants provided than just the ones given as examples in the section heading. If the heading ends ... then this means there are likely more; the exact constants provided will depend on the OS and headers found at compile-time. iykyk ๐
๐ง PF_INET, PF_INET6, PF_UNIX, ...
Protocol family constants to use as the first argument to socket() or the value of the SO_DOMAIN or SO_FAMILY socket option.
๐ AF_INET, AF_INET6, AF_UNIX, ...
Address family constants used by the socket address structures, to pass to such functions as inet_pton() or getaddrinfo(), or are returned by such functions as sockaddr_family().
๐ฆ SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ...
Socket type constants to use as the second argument to socket(), or the value of the SO_TYPE socket option.
๐ SOCK_NONBLOCK. SOCK_CLOEXEC
Linux-specific shortcuts to specify the O_NONBLOCK and FD_CLOEXEC flags during a socket(2) call.
socket( my $sockh, PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0 )
๐ SOL_SOCKET
Socket option level constant for setsockopt() and getsockopt().
๐ SO_ACCEPTCONN, SO_BROADCAST, SO_ERROR, ...
Socket option name constants for setsockopt() and getsockopt() at the SOL_SOCKET level.
๐ฅ IP_OPTIONS, IP_TOS, IP_TTL, ...
Socket option name constants for IPv4 socket options at the IPPROTO_IP level.
โญ IP_PMTUDISC_WANT, IP_PMTUDISC_DONT, ...
Socket option value constants for IP_MTU_DISCOVER socket option.
๐ IPTOS_LOWDELAY, IPTOS_THROUGHPUT, IPTOS_RELIABILITY, ...
Socket option value constants for IP_TOS socket option.
๐ธ MSG_BCAST, MSG_OOB, MSG_TRUNC, ...
Message flag constants for send() and recv().
โจ SHUT_RD, SHUT_RDWR, SHUT_WR
Direction constants for shutdown().
๐ INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE
Constants giving the special AF_INET addresses for wildcard, broadcast, local loopback, and invalid addresses.
Normally equivalent to inet_aton('0.0.0.0'), inet_aton('255.255.255.255'), inet_aton('localhost') and inet_aton('255.255.255.255') respectively.
๐ซถ IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, ...
IP protocol constants to use as the third argument to socket(), the level argument to getsockopt() or setsockopt(), or the value of the SO_PROTOCOL socket option.
๐ TCP_CORK, TCP_KEEPALIVE, TCP_NODELAY, ...
Socket option name constants for TCP socket options at the IPPROTO_TCP level.
๐ง IN6ADDR_ANY, IN6ADDR_LOOPBACK
Constants giving the special AF_INET6 addresses for wildcard and local loopback.
Normally equivalent to inet_pton(AF_INET6, "::") and inet_pton(AF_INET6, "::1") respectively.
๐ IPV6_ADD_MEMBERSHIP, IPV6_MTU, IPV6_V6ONLY, ...
Socket option name constants for IPv6 socket options at the IPPROTO_IPV6 level.
๐ธ STRUCTURE MANIPULATORS ๐ธ
okay bestie, so these next functions are the little translators between lists of Perl values and packed binary strings that represent structs. it's giving "glow up for raw bytes" โจ
๐ฆ sockaddr_family
$family = sockaddr_family $sockaddr;
You hand it a packed socket address โ like the ones pack_sockaddr_in(), pack_sockaddr_un(), or the Perl builtin functions getsockname() and getpeername() hand you back โ and it tells you the address family tag. That tag is gonna be one of the "AF_*" constants, e.g. "AF_INET" for a sockaddr_in address, or "AF_UNIX" for a sockaddr_un one.
so likeโฆ this is literally the function you use to figure out which unpack to reach for when you got a sockaddr but no idea what type it is ๐
๐ pack_sockaddr_in
$sockaddr = pack_sockaddr_in $port, $ip_address;
Two args, no biggie: a port number and an opaque string (the kind inet_aton() gives you, or a v-string). It returns the sockaddr_in structure with both of those packed on in there and "AF_INET" filled in. For Internet domain sockets this is the structure you normally need for the arguments in bind(), connect(), and send().
heads up: an undefined$portargument gets treated as zero. an undefined$ip_address?? that's a fatal error, no cap ๐ญ
๐ unpack_sockaddr_in
($port, $ip_address) = unpack_sockaddr_in $sockaddr;
Hands back a list of exactly two elements: the port, and an opaque string representing the IP address (use inet_ntoa() if you wanna get that four-dotted numeric format). It'll croak if the structure doesn't actually represent an "AF_INET" address, so like, don't play with it.
oh and โ in scalar context it returns just the IP address. cute, right? ๐ซถ
๐ sockaddr_in
$sockaddr = sockaddr_in $port, $ip_address;
($port, $ip_address) = sockaddr_in $sockaddr;
A wrapper of pack_sockaddr_in() or unpack_sockaddr_in(). In list context, it unpacks its argument and returns a list of the port and IP address. In scalar context, it packs its port and IP address arguments as a sockaddr_in and returns that.
Provided largely for legacy compatibility โ so like, it's the old faithful, but honestly bestie it's better to use pack_sockaddr_in() or unpack_sockaddr_in() explicitly. main character energy = being specific ๐
โจ pack_sockaddr_in6
$sockaddr = pack_sockaddr_in6 $port, $ip6_address,
$scope_id = 0, $flowinfo = 0;
Takes two to four arguments: a port number, an opaque string (as returned by inet_pton()), optionally a scope ID number, and optionally a flow label number. Returns the sockaddr_in6 structure with all that packed in and "AF_INET6" filled in. It's the IPv6 equivalent of pack_sockaddr_in() โ the upgraded version, as she deserves ๐
same rules as her IPv4 sister: undefined$portโ taken as zero; undefined$ip6_addressโ fatal error, bestie, don't ๐
๐ฆ unpack_sockaddr_in6
($port, $ip6_address, $scope_id, $flowinfo) = unpack_sockaddr_in6 $sockaddr;
Takes a sockaddr_in6 structure, gives you back a list of four elements: the port number, an opaque string representing the IPv6 address, the scope ID, and the flow label. (Use inet_ntop() if you wanna convert the address to the usual string format.) Will croak if the structure doesn't represent an "AF_INET6" address.
And again โ in scalar context you just get the IP address back ๐
๐ง sockaddr_in6
$sockaddr = sockaddr_in6 $port, $ip6_address,
$scope_id = 0, $flowinfo = 0;
($port, $ip6_address, $scope_id, $flowinfo) = sockaddr_in6 $sockaddr;
A wrapper of pack_sockaddr_in6() or unpack_sockaddr_in6(). In list context it unpacks its argument according to unpack_sockaddr_in6(). In scalar context it packs its arguments according to pack_sockaddr_in6().
Also largely for legacy compatibility โ again, better to use pack_sockaddr_in6() or unpack_sockaddr_in6() explicitly, iykyk ๐ธ
๐ธ pack_sockaddr_un
$sockaddr = pack_sockaddr_un $path;
One argument: a pathname. Returns the sockaddr_un structure with that path packed in and "AF_UNIX" filled in. For PF_UNIX sockets, this is normally the structure you need for the arguments in bind(), connect(), and send(). Unix domain socket girlies, this one's for you ๐
๐ unpack_sockaddr_un
($path) = unpack_sockaddr_un $sockaddr;
Takes a sockaddr_un structure (like the ones from pack_sockaddr_un(), getpeername() or recv()). Returns a list of one element: the pathname. Will croak if the structure doesn't represent an "AF_UNIX" address.
๐ sockaddr_un
$sockaddr = sockaddr_un $path;
($path) = sockaddr_un $sockaddr;
A wrapper of pack_sockaddr_un() or unpack_sockaddr_un(). In a list context it unpacks its argument and returns a list consisting of the pathname. In a scalar context it packs its pathname as a sockaddr_un and returns it.
Largely for legacy compatibility โ you already know the drill, bestie: use pack_sockaddr_un() or unpack_sockaddr_un() explicitly โจ
๐จ lowkey important: these are only supported if your system has <sys/un.h>. no header, no vibes, periodt.
๐ pack_ip_mreq
$ip_mreq = pack_ip_mreq $multiaddr, $interface;
Takes an IPv4 multicast address and optionally an interface address (or "INADDR_ANY"). Returns the ip_mreq structure with those arguments packed in. Perfect fit for use with the "IP_ADD_MEMBERSHIP" and "IP_DROP_MEMBERSHIP" sockopts ๐ฅ
๐ unpack_ip_mreq
($multiaddr, $interface) = unpack_ip_mreq $ip_mreq;
Takes an ip_mreq structure. Returns a list of two elements: the IPv4 multicast address and the interface address.
๐ pack_ip_mreq_source
$ip_mreq_source = pack_ip_mreq_source $multiaddr, $source, $interface;
Takes an IPv4 multicast address, a source address, and optionally an interface address (or "INADDR_ANY"). Returns the ip_mreq_source structure with everything packed in. Suitable for use with the "IP_ADD_SOURCE_MEMBERSHIP" and "IP_DROP_SOURCE_MEMBERSHIP" sockopts ๐ฆ
๐ unpack_ip_mreq_source
($multiaddr, $source, $interface) = unpack_ip_mreq_source $ip_mreq;
Takes an ip_mreq_source structure. Returns a list of three elements: the IPv4 multicast address, source address and interface address. three-for-one, we love to see it โจ
๐ pack_ipv6_mreq
$ipv6_mreq = pack_ipv6_mreq $multiaddr6, $ifindex;
Takes an IPv6 multicast address and an interface number. Returns the ipv6_mreq structure with those arguments packed in. Suitable for use with the "IPV6_ADD_MEMBERSHIP" and "IPV6_DROP_MEMBERSHIP" sockopts ๐
๐ง unpack_ipv6_mreq
($multiaddr6, $ifindex) = unpack_ipv6_mreq $ipv6_mreq;
Takes an ipv6_mreq structure. Returns a list of two elements: the IPv6 address and an interface number. short, sweet, iconic ๐
โจ FUNCTIONS โจ
๐ inet_aton
$ip_address = inet_aton $string;
Okay so bestie, inet_aton takes a string that's either a hostname or a textual representation of an IP address, and it translates that into a packed binary address structure โ the exact kind of thing you'd hand over to pack_sockaddr_in(). If you pass it a hostname that cannot be resolved, it returns undef. And for multi-homed hosts (aka hosts with more than one address), the first address found is what you get. Periodt.
For portability, do not assume that the result of inet_aton() is 32 bits wide โ in other words, don't assume it would contain only the IPv4 address in network order.
This function is IPv4-only and is provided largely for legacy reasons. Newly-written code should use getaddrinfo() or inet_pton() instead for IPv6 support.
๐ธ inet_ntoa
$string = inet_ntoa $ip_address;
Takes a packed binary address structure such as returned by unpack_sockaddr_in() (or a v-string representing the four octets of the IPv4 address in network order) and translates it into a string of the form d.d.d.d where the ds are numbers less than 256 (the normal human-readable four dotted number notation for Internet addresses).
This function is IPv4-only and is provided largely for legacy reasons. Newly-written code should use getnameinfo() or inet_ntop() instead for IPv6 support.
๐ฆ inet_pton
$address = inet_pton $family, $string;
Takes an address family (such as AF_INET or AF_INET6) and a string containing a textual representation of an address in that family, and translates that into a packed binary address structure.
See also getaddrinfo() for a more powerful and flexible function to look up socket addresses given hostnames or textual addresses.
๐ง inet_ntop
$string = inet_ntop $family, $address;
Takes an address family and a packed binary address structure and translates it into a human-readable textual representation of the address; typically in d.d.d.d form for AF_INET or hhhh:hhhh::hhhh form for AF_INET6.
See also getnameinfo() for a more powerful and flexible function to turn socket addresses into human-readable textual representations.
๐
getaddrinfo
($err, @result) = getaddrinfo $host, $service;
($err, @result) = getaddrinfo $host, $service, \%hints;
Given both a hostname and service name, this function attempts to resolve the host name into a list of network addresses, and the service name into a protocol and port number, and then returns a list of address structures suitable to connect() to it.
Given just a host name, this function attempts to resolve it to a list of network addresses, and then returns a list of address structures giving these addresses.
Given just a service name, this function attempts to resolve it to a protocol and port number, and then returns a list of address structures that represent it suitable to bind() to. This use should be combined with the AI_PASSIVE flag; see below.
Given neither name, it generates an error.
If present, $hints should be a reference to a hash, where the following keys are recognised:
flags => INTโ A bitfield containingAI_*constants; see below.family => INTโ Restrict to only generating addresses in this address family.socktype => INTโ Restrict to only generating addresses of this socket type.protocol => INTโ Restrict to only generating addresses for this protocol.
The return value will be a list; the first value being an error indication, followed by a list of address structures (if no error occurred).
The error value will be a dualvar; comparable to the EAI_* error constants, or printable as a human-readable error message string. If no error occurred it will be zero numerically and an empty string.
Each value in the results list will be a hash reference containing the following fields:
family => INTโ The address family (e.g.AF_INET).socktype => INTโ The socket type (e.g.SOCK_STREAM).protocol => INTโ The protocol (e.g.IPPROTO_TCP).addr => STRINGโ The address in a packed string (such as would be returned bypack_sockaddr_in()).canonname => STRINGโ The canonical name for the host if theAI_CANONNAMEflag was provided, orundefotherwise. This field will only be present on the first returned address.
The following flag constants are recognised in the $hints hash. Other flag constants may exist as provided by the OS.
AI_PASSIVEโ Indicates that this resolution is for a localbind()for a passive (i.e. listening) socket, rather than an active (i.e. connecting) socket.AI_CANONNAMEโ Indicates that the caller wishes the canonical hostname (canonname) field of the result to be filled in.AI_NUMERICHOSTโ Indicates that the caller will pass a numeric address, rather than a hostname, and thatgetaddrinfo()must not perform a resolve operation on this name. This flag will prevent a possibly-slow network lookup operation, and instead return an error if a hostname is passed.
๐ getnameinfo
($err, $hostname, $servicename) = getnameinfo $sockaddr,
$flags = 0, $xflags = 0;
Given a packed socket address (such as from getsockname(), getpeername(), or returned by getaddrinfo() in a addr field), returns the hostname and symbolic service name it represents. $flags may be a bitmask of NI_* constants, or defaults to 0 if unspecified.
The return value will be a list; the first value being an error condition, followed by the hostname and service name.
The error value will be a dualvar; comparable to the EAI_* error constants, or printable as a human-readable error message string. The host and service names will be plain strings.
The following flag constants are recognised as $flags. Other flag constants may exist as provided by the OS.
NI_NUMERICHOSTโ Requests that a human-readable string representation of the numeric address be returned directly, rather than performing a name resolve operation that may convert it into a hostname. This will also avoid potentially-blocking network IO.NI_NUMERICSERVโ Requests that the port number be returned directly as a number representation rather than performing a name resolve operation that may convert it into a service name.NI_NAMEREQDโ If a name resolve operation fails to provide a name, then this flag will causegetnameinfo()to indicate an error, rather than returning the numeric representation as a human-readable string.NI_DGRAMโ Indicates that the socket address relates to aSOCK_DGRAMsocket, for the services whose name differs between TCP and UDP protocols.
The following constants may be supplied as $xflags.
NIx_NOHOSTโ Indicates that the caller is not interested in the hostname of the result, so it does not have to be converted.undefwill be returned as the hostname.NIx_NOSERVโ Indicates that the caller is not interested in the service name of the result, so it does not have to be converted.undefwill be returned as the service name.
๐ getaddrinfo() / getnameinfo() ERROR CONSTANTS ๐
The following constants may be returned by getaddrinfo() or getnameinfo(). Others may be provided by the OS.
EAI_AGAINโ A temporary failure occurred during name resolution. The operation may be successful if it is retried later.EAI_BADFLAGSโ The value of theflagshint togetaddrinfo(), or the$flagsparameter togetnameinfo()contains unrecognised flags.EAI_FAMILYโ Thefamilyhint togetaddrinfo(), or the family of the socket address passed togetnameinfo()is not supported.EAI_NODATAโ The host name supplied togetaddrinfo()did not provide any usable address data.EAI_NONAMEโ The host name supplied togetaddrinfo()does not exist, or the address supplied togetnameinfo()is not associated with a host name and theNI_NAMEREQDflag was supplied.EAI_SERVICEโ The service name supplied togetaddrinfo()is not available for the socket type given in the$hints.
โจ EXAMPLES โจ
Okay bestie this is the part where it all comes together, the little recipe book, the vibe section ๐ everything below is real working code, copy it, love it, run it.
๐ Lookup for connect()
So the getaddrinfo() function does the glow-up of turning a hostname + a service name into a whole list of structures, and each one of those lil structs is a possible way to connect() to that named service on that named host. It's giving "here are all your options, choose wisely" ๐
use IO::Socket;
use Socket qw(SOCK_STREAM getaddrinfo);
my %hints = (socktype => SOCK_STREAM);
my ($err, @res) = getaddrinfo("localhost", "echo", \%hints);
die "Cannot getaddrinfo - $err" if $err;
my $sock;
foreach my $ai (@res) {
my $candidate = IO::Socket->new();
$candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})
or next;
$candidate->connect($ai->{addr})
or next;
$sock = $candidate;
last;
}
die "Cannot connect to localhost:echo" unless $sock;
$sock->print("Hello, world!\n");
print <$sock>;
Because a whole list of potential candidates comes back, the "while" loop is out here doing speed-dating, trying each one in turn until it finds one that succeeds both the socket() AND the connect() calls. Periodt. ๐ฆ
This function performs the work of the legacy functions gethostbyname(), getservbyname(), inet_aton() and pack_sockaddr_in().
ngl, in practice this logic is better performed by IO::Socket::IP โ that's the main character here, fr fr.
๐ Making a human-readable string out of an address
The getnameinfo() function takes a socket address (like the ones getsockname() or getpeername() hand you) and converts it into a pair of human-readable strings โ one for the address, one for the service name. Iconic โจ
use IO::Socket::IP;
use Socket qw(getnameinfo);
my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or
die "Cannot listen - $@";
my $socket = $server->accept or die "accept: $!";
my ($err, $hostname, $servicename) = getnameinfo($socket->peername);
die "Cannot getnameinfo - $err" if $err;
print "The peer is connected from $hostname\n";
Since in this example only the hostname was actually used, that redundant little conversion of the port number into a service name is giving unnecessary, and you can skip it by passing the "NIx_NOSERV" flag. ๐
use Socket qw(getnameinfo NIx_NOSERV);
my ($err, $hostname) = getnameinfo($socket->peername, 0, NIx_NOSERV);
This function performs the work of the legacy functions unpack_sockaddr_in(), inet_ntoa(), gethostbyaddr() and getservbyport().
Again bestie โ in practice this logic is better performed by IO::Socket::IP. Just saying ๐คทโโ๏ธ
๐ Resolving hostnames into IP addresses
Wanna turn a hostname into a human-readable plain IP address? The move is: use getaddrinfo() to turn the hostname into a list of socket structures, then run getnameinfo() on each one to make it a readable IP address again. Full circle moment, we love a loop ๐ฅ
use Socket qw(:addrinfo SOCK_RAW);
my ($err, @res) = getaddrinfo($hostname, "", {socktype => SOCK_RAW});
die "Cannot getaddrinfo - $err" if $err;
while( my $ai = shift @res ) {
my ($err, $ipaddr) = getnameinfo($ai->{addr}, NI_NUMERICHOST, NIx_NOSERV);
die "Cannot getnameinfo - $err" if $err;
print "$ipaddr\n";
}
The "socktype" hint to getaddrinfo() filters the results so only one socket type and protocol comes through. Without it, most OSes will hit you with three combinations โ for "SOCK_STREAM", "SOCK_DGRAM" and "SOCK_RAW" โ which means triplicate output of addresses, i.e. the same address three times, we do NOT claim that ๐
And the "NI_NUMERICHOST" flag to getnameinfo() is what makes it return a string-formatted plain IP address instead of reverse resolving it back into a hostname. No cap. ๐ง
This combination performs the work of the legacy functions gethostbyname() and inet_ntoa().
๐ Accessing socket options
All those many "SO_*" and other constants? They're literally serving up the socket option names for getsockopt() and setsockopt(). So convenient, obsessed. ๐
use IO::Socket::INET;
use Socket qw(SOL_SOCKET SO_RCVBUF IPPROTO_IP IP_TTL);
my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')
or die "Cannot create socket: $@";
$socket->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024) or
die "setsockopt: $!";
print "Receive buffer is ", $socket->getsockopt(SOL_SOCKET, SO_RCVBUF),
" bytes\n";
print "IP TTL is ", $socket->getsockopt(IPPROTO_IP, IP_TTL), "\n";
As a lil convenience, IO::Socket's setsockopt() method will convert a number into a packed byte buffer, and getsockopt() will unpack a byte buffer of the correct size right back into a number. It's giving effortless ๐ซ
๐ AUTHOR ๐
This module was originally maintained in Perl core by the Perl 5 Porters.
It was extracted to dual-life on CPAN at version 1.95 by Paul Evans <leonerd@leonerd.org.uk> โ shoutout, legend behaviour ๐ซถ
And that's the whole page bestie!! ๐ธ You just read Socket(3perl) as shipped with perl v5.44.0, dated 2026-10-17. Go forth, open sockets, close them responsibly, and remember: use Socket; is a lifestyle ๐โจ๐งโโ๏ธ
๐ฆ where this page comes from
- arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms