--- name: recv signature: 'recv SOCKET,SCALAR,LENGTH,FLAGS' since: 5.0 status: documented categories: ["Sockets"] --- ```{index} single: recv; Perl built-in ``` *[Sockets](../perlfunc-by-category)* # 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 ```perl 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`](../../Socket)'s `sockaddr_in`, `sockaddr_in6`, or `sockaddr_un` depending 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 with [`defined`](defined), not plain truthiness. - On error: [`undef`](undef), with [`$!`](../perlvar) set to the `errno` from the failing `recvfrom(2)` call. Typical errors: `EAGAIN` / `EWOULDBLOCK` on a non-blocking socket with no data ready, `ECONNRESET` on a TCP peer reset, `EBADF` on 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 - [`$!`](../perlvar) is set on error to the system `errno`. - No other special variables are involved. `recv` does not honour [`$/`](../perlvar), [`$,`](../perlvar), or [`$\`](../perlvar) — those are line-oriented I/O concepts and `recv` is a raw datagram / byte-stream primitive. ## Examples Read one UDP datagram and identify the sender: ```perl 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`](defined) rather than boolean truth: ```perl 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: ```perl 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: ```perl 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: ```perl 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 `SOCKET` has a `:utf8` layer (directly or via `:encoding(...)`), `recv` throws an exception. `recv` is byte-oriented and does not interact with PerlIO layers; use [`binmode`](binmode) to strip the layer before reading, or decode the resulting bytes yourself. - **LENGTH vs datagram size**: for datagram sockets, if `LENGTH` is 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**: `recv` on a connected socket returns the empty string, which `!` treats as false. Code like `recv(...) or die $!` dies on every successful connected read. Use [`defined`](defined): ```perl defined(recv($sock, $buf, $len, 0)) or die "recv: $!"; ``` - **Zero-byte result on a stream socket**: `recv` returns `""` and `SCALAR` becomes empty when the peer has performed an orderly shutdown. Distinguish end-of-stream from a real error by checking `length($buf) == 0` after a defined return. - **Signals**: a blocking `recv` interrupted by a signal returns [`undef`](undef) with [`$!`](../perlvar) == `EINTR`. Retry or install a proper [`sigaction`](../../POSIX/sigaction) with `SA_RESTART` if that's not what you want. - **Closed socket**: `recv` on a closed or never-opened handle returns [`undef`](undef), sets [`$!`](../perlvar) to `EBADF`, and emits a `recv() on closed socket` warning under `use warnings`. - **Pre-existing `SCALAR` contents are destroyed**. `recv` does 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`](send) — the write side of the same socket; same `FLAGS` vocabulary, same connectionless-vs-connected distinction - [`socket`](socket) — create the `SOCKET` handle `recv` reads from - [`bind`](bind) — required before `recv` on a server-side datagram socket so the kernel knows which port to deliver to - [`connect`](connect) — when used on a datagram socket, makes `recv` return `""` like a stream socket and filters out datagrams from other peers - [`sysread`](sysread) — byte-level read for stream sockets when you do not need the sender address; integrates with `select`-based loops - [`Socket`](../../Socket) — `sockaddr_in`, `inet_ntoa`, `MSG_PEEK`, `MSG_WAITALL`, and the rest of the constants `recv` consumes