IO::Socket(3perl)
π IO::Socket β the perl manual page, but make it cute π
okay bestie, welcome to IO::Socket(3perl), straight outta the Perl Programmers Reference Guide. this is the section 3 man page for IO::Socket, and no cap, it's a whole mood. grab a strawberry π and let's go.
β¨ NAME β¨
IO::Socket β Object interface to socket communications π¦
like. sockets. but object-y. you're welcome.
πΈ SYNOPSIS πΈ
here's the vibe, verbatim, don't touch my code:
use strict;
use warnings;
use IO::Socket qw(AF_INET AF_UNIX);
# create a new AF_INET socket
my $sock = IO::Socket->new(Domain => AF_INET);
# which is the same as
$sock = IO::Socket::INET->new();
# create a new AF_UNIX socket
$sock = IO::Socket->new(Domain => AF_UNIX);
# which is the same as
$sock = IO::Socket::UNIX->new();
see how the second one is literally just a glow-up disguise for the first one? it's giving same girl, different outfit π
π DESCRIPTION π
okay so IO::Socket hands you an object-oriented, IO::Handle-based interface for creating and using sockets β and it does that through Socket, which is basically a near one-to-one mirror of the C socket library. so if you already know C sockets, you're gonna feel right at home. iconic behavior.
IO::Socket is a base class, and it really only defines methods for stuff that's common to all socket types. the stuff that's specific to one particular socket domain? that lives in subclasses of IO::Socket. for examples of those subclass girlies, go peek at IO::Socket::INET, IO::Socket::UNIX, and IO::Socket::IP.
and omg β IO::Socket will export all functions (and constants) defined by Socket. all of them. no crumbs left behind π«Ά
π CONSTRUCTOR ARGUMENTS π
so IO::Socket doesn't have attributes in the traditional sense β rude of it, honestly β so instead of attributes you pass these arguments into the constructor.
constructor arguments get passed in Key => 'Value' pairs, bestie. very demure. very mindful.
the only required argument is Domain in IO::Socket. everything else is optional. periodt.
π€ Blocking
my $sock = IO::Socket->new(..., Blocking => 1);
$sock = IO::Socket->new(..., Blocking => 0);
if it's defined but false, the socket gets set into non-blocking mode. if you just... don't specify it at all, it defaults to 1 (blocking mode). so blocking is the main character unless you say otherwise β¨
π Domain
my $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
$sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
the socket domain decides which subclass of IO::Socket you're gonna use. the two options shipping along with this distribution are AF_INET and AF_UNIX.
AF_INET is for the internet address family of sockets, and it's handled via IO::Socket::INET. AF_INET sockets get bound to an internet address and port. very online of them.
AF_UNIX is for the unix domain socket, handled via IO::Socket::UNIX. AF_UNIX sockets are bound to the file system as their address name space. yes, the filesystem. they live there. rent free π
important!! this argument is required. all other arguments are optional. don't forget her or she'll ghost you.
π Listen
my $sock = IO::Socket->new(..., Listen => 5);
Listen should be an integer value, or just left unset. no in-between.
if you do provide it, this argument places the socket into listening mode. new connections can then be accepted using the "accept" in IO::Socket method π§. the value you give is used as the listen(2) queue size.
oh and β if the Listen argument is given but it's false, the queue size gets set to 5. surprise surprise, she picks for you.
β³ Timeout
my $sock = IO::Socket->new(..., Timeout => 5);
the timeout value, in seconds, for this socket connection. how exactly that value gets utilized is defined over in the socket domain subclasses that actually make use of it. so like, don't @ me, @ the subclass π
π Type
my $sock = IO::Socket->new(..., Type => IO::Socket::SOCK_STREAM);
the socket type that'll be used. these are usually SOCK_STREAM, SOCK_DGRAM, or SOCK_RAW. if you leave this argument undefined, an attempt will be made to infer the type from the service name. she'll figure it out herself, slay.
for example, you'll usually use SOCK_STREAM with a tcp connection and SOCK_DGRAM with a udp connection. match made in heaven, no cap π
π§ CONSTRUCTORS π§
IO::Socket extends the IO::Handle constructor. family tree stay winning.
β new
my $sock = IO::Socket->new();
# get a new IO::Socket::INET instance
$sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
# get a new IO::Socket::UNIX instance
$sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
# Domain is the only required argument
$sock = IO::Socket->new(
Domain => IO::Socket::AF_INET, # AF_INET, AF_UNIX
Type => IO::Socket::SOCK_STREAM, # SOCK_STREAM, SOCK_DGRAM, ...
Proto => 'tcp', # 'tcp', 'udp', IPPROTO_TCP, IPPROTO_UDP
# and so on...
);
creates an IO::Socket, which is a reference to a newly created symbol (see the Symbol package, iykyk). new optionally takes arguments, and those arguments are defined in "CONSTRUCTOR ARGUMENTS" in IO::Socket.
any of the "CONSTRUCTOR ARGUMENTS" in IO::Socket may be passed to the constructor β but if you provide any arguments at all, then one of them has to be the "Domain" in IO::Socket argument. by default, that "Domain" in IO::Socket argument can be either AF_INET or AF_UNIX. other domains are usable if a proper subclass for that domain family has been registered. and all the other arguments? they get passed along to the "configuration" method of the package for that domain. teamwork makes the dream work π«Ά
if the constructor fails it will return undef and set the $errstr package variable to contain an error message. so:
$sock = IO::Socket->new(...)
or die "Cannot create socket - $IO::Socket::errstr\n";
and for legacy reasons β the drama of it all β the error message is also set into the global $@ variable, and you may still find older code which looks here instead:
$sock = IO::Socket->new(...)
or die "Cannot create socket - $@\n";
so like, $IO::Socket::errstr is the new girl and $@ is the older sister who still has a key to the house. both work. don't judge. π
π METHODS π
okay so here's the tea: IO::Socket inherits every single method from IO::Handle, and then it's like "and ALSO" and serves you these brand new ones. no cap. π«Ά
πΈ accept
my $client_sock = $sock->accept();
my $inet_sock = $sock->accept('IO::Socket::INET');
so accept does the literal system call accept on the socket and hands you back a shiny new object β¨. that new object gets created in the same class as the listen socket, unless you name a specific package β then it's that one bestie. you use this object to actually talk to the client that was trying to connect. it's giving "welcome in, we've been expecting you" π
this differs slightly from the accept function in perlfunc, jsyk.
in scalar context you get the new socket, or undef if it flopped π. in list context you get a two-element array with the new socket and the peer address β and if it fails, that list is justβ¦ empty π.
scalar β one socket Β· list β socket + peer address
π atmark
my $integer = $sock->atmark();
# read in some data on a given socket
my $data;
$sock->read($data, 1024) until $sock->atmark;
# or, export the function to use:
use IO::Socket 'sockatmark';
$sock->read($data, 1024) until sockatmark($sock);
returns true if the socket is currently posted up at the urgent data mark, false otherwise. and if your system hasn't implemented sockatmark yet? it throws an exception π.
lowkey important: if your system doesn't supportsockatmark, thatusedeclaration fails at compile time. so like, it's not a runtime surprise, it's a right now surprise. π
β¨ autoflush
# by default, autoflush will be turned on when referenced
$sock->autoflush(); # turns on autoflush
# turn off autoflush
$sock->autoflush(0);
# turn on autoflush
$sock->autoflush(1);
so this attribute isn't actually overridden from IO::Handle's implementation β it's the same one. but because we turn it on by default, it's highkey worth a mention right here. consider this your reminder text π«Ά
π¦ bind
use Socket qw(pack_sockaddr_in);
my $port = 3000;
my $ip_address = '0.0.0.0';
my $packed_addr = pack_sockaddr_in($port, $ip_address);
$sock->bind($packed_addr);
binds a network address to a socket, exactly like bind(2) does. returns true if it slayed, false otherwise. and bestie β you gotta hand it a packed address of the appropriate type for that socket. that part is not optional, the socket will simply not know what you mean. π
π connected
my $peer_addr = $sock->connected();
if ($peer_addr) {
say "We're connected to $peer_addr";
}
if the socket is in a connected state, you get the peer address back. if it's not, you get undef. simple, right? β¦okay not so simple, keep reading π
β οΈ the caveat section, do not skip: this method considers a half-open TCP socket to be "in a connected state". specifically, it does not distinguish between the ESTABLISHED and CLOSE-WAIT TCP states β it returns the peer address, rather thanundef, in either case. so in general, it cannot be used to reliably learn whether the peer has initiated a graceful shutdown, because in most cases (see below) the local TCP state machine remains in CLOSE-WAIT until the local application callsshutdownin IO::Socket orclose. only at that point does this function returnundef.
and the "in most cases" hedge? that's there because local TCP state machine behavior may depend on the peer's socket options. in particular, if the peer socket has SO_LINGER enabled with a zero timeout, then the peer's close will generate a RST segment. upon receipt of that segment, the local TCP transitions immediately to CLOSED β and in that state, this method will return undef. so like, sometimes it does what you want. sometimes. π
π getsockopt
my $value = $sock->getsockopt(SOL_SOCKET, SO_REUSEADDR);
my $buf = $socket->getsockopt(SOL_SOCKET, SO_RCVBUF);
say "Receive buffer is $buf bytes";
gets an option associated with the socket. you can specify levels other than SOL_SOCKET here too. and as a lil convenience, this method will unpack a byte buffer of the correct size back into a number for you, so you don't have to do it yourself like some sort of cave gremlin. π
π listen
$sock->listen(5);
does the exact same thing the listen(2) system call does. returns true if it worked, false otherwise. listens to a socket with a given queue size β that's the number you're passing in. five in this example, but that's your call bestie π
π§ peername
my $sockaddr_in = $sock->peername();
returns the packed sockaddr address of the other end of the socket connection. it calls getpeername under the hood, so it's giving "who's on the other side of this wire" πΈ
π protocol
my $proto = $sock->protocol();
returns the number for the protocol being used on the socket, if it's known. if the protocol is unknown β like, say, with an AF_UNIX socket β then zero is returned. not undef, not an error, just a chill little 0. β
π recv
my $buffer = "";
my $length = 1024;
my $flags = 0; # default. optional
$sock->recv($buffer, $length);
$sock->recv($buffer, $length, $flags);
similar in functionality to recv in perlfunc π«Ά
receives a message on a socket. it attempts to receive $length characters of data into $buffer from the specified socket. $buffer will be grown or shrunk to the length actually read β so it's not gonna stay a liar, it resizes to the truth. takes the same flags as the system call of the same name. returns the address of the sender if the socket's protocol supports that; returns an empty string otherwise. if there's an error, returns undef. and fun fact, this call is actually implemented in terms of the recvfrom(2) system call. β¨
flags are ORed together values, such as MSG_BCAST, MSG_OOB, MSG_TRUNC. the default value for the flags is 0.
the cached value of peername in IO::Socket is updated with the result of recv. so it stays current, queen π
Note: in Perl v5.30 and newer, if the socket has been marked as:utf8,recvwill throw an exception. the :encoding(...) layer implicitly introduces the:utf8layer. seebinmodein perlfunc.
Note: in Perl versions older than v5.30, depending on the status of the socket, either (8-bit) bytes or characters are received. by default all sockets operate on bytes, but for example if the socket has been changed usingbinmodein perlfunc to operate with the :encoding(UTF-8) I/O layer (see theopenin perlfunc pragma), the I/O will operate on UTF8-encoded Unicode characters, not bytes. similarly for the:encodinglayer: in that case pretty much any characters can be read. π
π₯ send
my $message = "Hello, world!";
my $flags = 0; # defaults to zero
my $to = '0.0.0.0'; # optional destination
my $sent = $sock->send($message);
$sent = $sock->send($message, $flags);
$sent = $sock->send($message, $flags, $to);
similar in functionality to send in perlfunc π«Ά
sends a message on a socket. it attempts to send the scalar message to the socket. takes the same flags as the system call of the same name. on unconnected sockets, you must specify a destination to send to, in which case it does a sendto(2) syscall. returns the number of characters sent, or undef on error. also β the sendmsg(2) syscall is currently unimplemented. so don't go looking for it, it's not there bestie π
the flags option is optional and defaults to 0.
after a successful send with $to, further calls to send on an unconnected socket without $to will send to the same address, and $to will be used as the result of peername in IO::Socket. it remembers. iconic behavior honestly π
Note: in Perl v5.30 and newer, if the socket has been marked as:utf8,sendwill throw an exception. the :encoding(...) layer implicitly introduces the:utf8layer. seebinmodein perlfunc.
Note: in Perl versions older than v5.30, depending on the status of the socket, either (8-bit) bytes or characters are sent. by default all sockets operate on bytes, but for example if the socket has been changed usingbinmodein perlfunc to operate with the :encoding(UTF-8) I/O layer (see theopenin perlfunc pragma), the I/O will operate on UTF8-encoded Unicode characters, not bytes. similarly for the:encodinglayer: in that case pretty much any characters can be sent. π
π setsockopt
$sock->setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
$sock->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024);
sets an option associated with the socket. levels other than SOL_SOCKET may absolutely be specified here. and as a convenience, this method will convert a number into a packed byte buffer for you, so you can just pass a plain number and vibe. β¨
πΈ shutdown
$sock->shutdown(SHUT_RD); # we stopped reading data
$sock->shutdown(SHUT_WR); # we stopped writing data
$sock->shutdown(SHUT_RDWR); # we stopped using this socket
shuts down a socket connection in the manner indicated by the value you pass in, which has the same interpretation as in the syscall of the same name.
this is useful with sockets when you wanna tell the other side you're done writing but not done reading, or vice versa. it's also a more insistent form of close, because it also disables the file descriptor in any forked copies in other processes. that's the part that makes it hit different π«Ά
returns 1 for success. on error: returns undef if the socket is not a valid filehandle, or returns 0 and sets $! for any other failure. noted, noted, noted. π
π¦ sockdomain
my $domain = $sock->sockdomain();
returns the number for the socket domain type. for example, for an AF_INET socket, the value of &AF_INET will be returned. cute and numeric, as promised. β
π socket
my $sock = IO::Socket->new(); # no values given
# now let's actually get a socket with the socket method
# domain, type, and protocol are required
$sock = $sock->socket(AF_INET, SOCK_STREAM, 'tcp');
opens a socket of the specified kind and returns it. domain, type, and protocol are specified the same as for the syscall of the same name β and yes, those three are required. no shortcuts bestie π
π§ socketpair
my ($r, $w) = $sock->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
($r, $w) = IO::Socket::UNIX
->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
will return a list of two sockets created (read and write), or an empty list on failure. two lil besties, one for reading and one for writing π«Ά
this differs slightly from socketpair in perlfunc in that the argument list is a bit simpler. less typing, same energy. β¨
π sockname
my $packed_addr = $sock->sockname();
returns the packed sockaddr address of this end of the connection. it's the same as getsockname(2). the mirror image of peername, basically. π
π sockopt
my $value = $sock->sockopt(SO_REUSEADDR);
$sock->sockopt(SO_REUSEADDR, 1);
the unified method to both set and get options in the SOL_SOCKET level. if you call it with one argument, then getsockopt in IO::Socket gets called. otherwise, setsockopt in IO::Socket gets called. one method, two moods. π
π socktype
my $type = $sock->socktype();
returns the number for the socket type. for example, for a SOCK_STREAM socket, the value of &SOCK_STREAM will be returned. β
πΈ timeout
my $seconds = $sock->timeout();
my $old_val = $sock->timeout(5); # set new and return old value
set or get the timeout value (in seconds) associated with this socket. if you call it with no arguments at all, then the current setting is returned. if you call it with an argument, the current setting gets changed and the previous value is returned β so you get a lil receipt of what it used to be. π
this method is available to all IO::Socket implementations, but it may or may not actually be used by the individual domain subclasses. so likeβ¦ it's there. whether it does something depends on who you're talking to bestie π«Ά
okay bestie, we've covered all the methods, so now let's put it all together and actually use this thing. it's giving main character energy, fr fr.
β¨ EXAMPLES β¨
so like, let's create a TCP server on localhost:3333. watch and learn, no cap.
use strict;
use warnings;
use feature 'say';
use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
my $server = IO::Socket->new(
Domain => AF_INET,
Type => SOCK_STREAM,
Proto => 'tcp',
LocalHost => '0.0.0.0',
LocalPort => 3333,
ReusePort => 1,
Listen => 5,
) || die "Can't open socket: $IO::Socket::errstr";
say "Waiting on 3333";
while (1) {
# waiting for a new client connection
my $client = $server->accept();
# get information about a newly connected client
my $client_address = $client->peerhost();
my $client_port = $client->peerport();
say "Connection from $client_address:$client_port";
# read up to 1024 characters from the connected client
my $data = "";
$client->recv($data, 1024);
say "received data: $data";
# write response data to the connected client
$data = "ok";
$client->send($data);
# notify client that response has been sent
$client->shutdown(SHUT_WR);
}
$server->close();
and a client for such a server? say less. here's one:
use strict;
use warnings;
use feature 'say';
use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
my $client = IO::Socket->new(
Domain => AF_INET,
Type => SOCK_STREAM,
proto => 'tcp',
PeerPort => 3333,
PeerHost => '0.0.0.0',
) || die "Can't open socket: $IO::Socket::errstr";
say "Sending Hello World!";
my $size = $client->send("Hello World!");
say "Sent data of length: $size";
$client->shutdown(SHUT_WR);
my $buffer;
$client->recv($buffer, 1024);
say "Got back $buffer";
$client->close();
π LIMITATIONS π
not everything is perfect, bestie. on some systems, if you made an IO::Socket object with new_from_fd, or if you made one with accept in IO::Socket from such an object, the protocol, sockdomain, and socktype methods might just return undef. it's giving mystery, and not in a fun way. π
π SEE ALSO π
go check these out, they're the besties of this module:
SocketIO::HandleIO::Socket::INETIO::Socket::UNIXIO::Socket::IP
π AUTHOR π
this masterpiece was written by Graham Barr. atmark() was by Lincoln Stein. currently maintained by the Perl 5 Porters. found a bug? please report all bugs at https://github.com/Perl/perl5/issues. we love a community effort, periodt.
π COPYRIGHT π
Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The atmark() implementation: Copyright 2001, Lincoln Stein <lstein@cshl.org>. This module is distributed under the same terms as Perl itself. Feel free to use, modify and redistribute it as long as you retain the correct attribution.
and that's the whole page, bestie! this one came from perl v5.44.0, dated 2026-10-17 β the IO::Socket(3perl) manpage. now go slay those sockets. π
β¨π¦
π¦ 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