recv#
Read an incoming message from a socket into a scalar.
recv reads up to LENGTH bytes from SOCKET into SCALAR, replacing
whatever SCALAR previously held. SCALAR is grown or shrunk to the
number of bytes actually received. FLAGS is the same bit mask the
underlying recvfrom(2) system call takes — 0 for ordinary
reads; the common non-zero values are MSG_PEEK (look without
consuming), MSG_WAITALL (block until LENGTH bytes arrive), and
MSG_DONTWAIT (never block). For a connectionless socket recv
returns the sender’s packed address; for a connected socket it returns
the empty string. Under the hood this is recvfrom(2), not recv(2).
Synopsis#
recv SOCKET, SCALAR, LENGTH, FLAGS
What you get back#
On success from a connectionless socket (UDP, UNIX datagram): the sender’s address as a packed sockaddr string. Unpack it with
Socket’ssockaddr_in,sockaddr_in6, orsockaddr_undepending on the address family.On success from a connected socket (TCP, connected UDP): the empty string
"". The empty string is true for the defined-vs-undef check but false in boolean context — test withdefined, not plain truthiness.On error:
undef, with$!set to theerrnofrom the failingrecvfrom(2)call. Typical errors:EAGAIN/EWOULDBLOCKon a non-blocking socket with no data ready,ECONNRESETon a TCP peer reset,EBADFon a closed handle.
SCALAR is always resized to the byte count read. A zero-byte read on
a connected stream socket means the peer closed its write side
cleanly — recv returns "" and SCALAR becomes the empty string.
Global state it touches#
Examples#
Read one UDP datagram and identify the sender:
use Socket;
my $from = recv($sock, my $buf, 1500, 0)
or die "recv: $!";
my ($port, $ip) = sockaddr_in($from);
print "got ", length($buf), " bytes from ",
inet_ntoa($ip), ":$port\n";
Read from a connected TCP socket. The sender address is empty, so
check with defined rather than boolean truth:
defined(recv($sock, my $buf, 4096, 0))
or die "recv: $!";
# $buf now holds 0..4096 bytes; 0 means the peer closed.
Peek at the next datagram without consuming it. The second call returns the same bytes:
use Socket;
recv($sock, my $peek, 1500, MSG_PEEK) or die $!;
recv($sock, my $consume, 1500, 0) or die $!;
# $peek and $consume hold the same datagram.
Non-blocking read loop. EAGAIN / EWOULDBLOCK is the normal “no
data yet” signal, not a real error:
use Errno qw(EAGAIN EWOULDBLOCK);
while (1) {
my $from = recv($sock, my $buf, 1500, 0);
unless (defined $from) {
last if $! == EAGAIN || $! == EWOULDBLOCK;
die "recv: $!";
}
handle_datagram($from, $buf);
}
Force a full-length read on a stream socket that might fragment the
message — MSG_WAITALL blocks until LENGTH bytes are in or the
connection dies:
use Socket;
defined(recv($sock, my $frame, 64, MSG_WAITALL))
or die "recv: $!";
# $frame is exactly 64 bytes, or the peer closed early.
Edge cases#
UTF-8-layered socket: if
SOCKEThas a:utf8layer (directly or via:encoding(...)),recvthrows an exception.recvis byte-oriented and does not interact with PerlIO layers; usebinmodeto strip the layer before reading, or decode the resulting bytes yourself.LENGTH vs datagram size: for datagram sockets, if
LENGTHis smaller than the incoming datagram, the excess is discarded silently. Size the buffer to the protocol’s MTU (typically 1500 for UDP over Ethernet, 65507 for the IPv4 UDP maximum).""return is not false-enough:recvon a connected socket returns the empty string, which!treats as false. Code likerecv(...) or die $!dies on every successful connected read. Usedefined:defined(recv($sock, $buf, $len, 0)) or die "recv: $!";
Zero-byte result on a stream socket:
recvreturns""andSCALARbecomes empty when the peer has performed an orderly shutdown. Distinguish end-of-stream from a real error by checkinglength($buf) == 0after a defined return.Signals: a blocking
recvinterrupted by a signal returnsundefwith$!==EINTR. Retry or install a propersigactionwithSA_RESTARTif that’s not what you want.Closed socket:
recvon a closed or never-opened handle returnsundef, sets$!toEBADF, and emits arecv() on closed socketwarning underuse warnings.Pre-existing
SCALARcontents are destroyed.recvdoes not append; it overwrites. Use a fresh lexical or clear the scalar before each call.
Differences from upstream#
Fully compatible with upstream Perl 5.42.
See also#
send— the write side of the same socket; sameFLAGSvocabulary, same connectionless-vs-connected distinctionsocket— create theSOCKEThandlerecvreads frombind— required beforerecvon a server-side datagram socket so the kernel knows which port to deliver toconnect— when used on a datagram socket, makesrecvreturn""like a stream socket and filters out datagrams from other peerssysread— byte-level read for stream sockets when you do not need the sender address; integrates withselect-based loopsSocket—sockaddr_in,inet_ntoa,MSG_PEEK,MSG_WAITALL, and the rest of the constantsrecvconsumes