Socket#

Native implementation of Perl’s Socket module

Provides socket-related constants and functions compatible with Perl’s Socket module. Since PetaPerl does not support XS, this module is implemented directly in Rust.

Synopsis#

use Socket qw(inet_aton inet_ntoa pack_sockaddr_in
              unpack_sockaddr_in getaddrinfo);

my $packed = inet_aton("127.0.0.1");
my $ip     = inet_ntoa($packed);

my $sockaddr = pack_sockaddr_in(80, inet_aton("127.0.0.1"));
my ($port, $addr) = unpack_sockaddr_in($sockaddr);

# Name resolution
my ($err, @res) = getaddrinfo("localhost", "http");

Constants#

Address families (AF_INET, AF_INET6, AF_UNIX, etc.), socket types (SOCK_STREAM, SOCK_DGRAM, etc.), protocol constants, and more.

Functions#

inet_aton#

Convert an IPv4 address string (dotted-quad or hostname) to a packed 4-byte binary address. Returns undef on failure.

use Socket 'inet_aton';
my $packed = inet_aton("127.0.0.1");

inet_ntoa#

Convert a packed 4-byte binary IPv4 address to a dotted-quad string.

use Socket 'inet_ntoa';
my $ip = inet_ntoa($packed);  # "127.0.0.1"

inet_pton#

Address-family-aware conversion of an IP address string to packed binary form. Supports AF_INET (4 bytes) and AF_INET6 (16 bytes).

use Socket qw(inet_pton AF_INET6);
my $packed = inet_pton(AF_INET6, "::1");

inet_ntop#

Address-family-aware conversion of a packed binary address to a string.

use Socket qw(inet_ntop AF_INET);
my $ip = inet_ntop(AF_INET, $packed);

pack_sockaddr_in#

Pack a port number and a packed IPv4 address into a sockaddr_in structure.

use Socket;
my $sockaddr = pack_sockaddr_in(80, inet_aton("127.0.0.1"));

unpack_sockaddr_in#

Unpack a sockaddr_in structure into a port number and packed IPv4 address.

use Socket;
my ($port, $addr) = unpack_sockaddr_in($sockaddr);

pack_sockaddr_in6#

Pack a port, packed IPv6 address, scope ID, and flow info into a sockaddr_in6 structure.

unpack_sockaddr_in6#

Unpack a sockaddr_in6 structure into port, address, scope ID, and flow info.

pack_sockaddr_un#

Pack a Unix domain socket path into a sockaddr_un structure.

use Socket 'pack_sockaddr_un';
my $sockaddr = pack_sockaddr_un("/tmp/my.sock");

unpack_sockaddr_un#

Extract the pathname from a sockaddr_un structure.

sockaddr_family#

Extract the address family (AF_INET, AF_INET6, AF_UNIX) from a packed sockaddr.

sockaddr_in#

Context-dependent: in list context, equivalent to unpack_sockaddr_in; with two arguments, equivalent to pack_sockaddr_in.

sockaddr_in6#

IPv6 equivalent of sockaddr_in.

getaddrinfo#

Resolve a hostname and service name to a list of socket address structures. Returns a list of hashrefs with keys: family, socktype, protocol, addr, canonname.

use Socket qw(getaddrinfo);
my ($err, @res) = getaddrinfo("localhost", "http");

getnameinfo#

Reverse-resolve a packed sockaddr to a hostname and service name.

use Socket qw(getnameinfo);
my ($err, $host, $service) = getnameinfo($sockaddr);