send#
Send a message on a socket.
send writes the scalar MSG to SOCKET through the operating
system’s socket layer, not through PerlIO. On a connected socket
(SOCK_STREAM after connect, or an accepted peer) the
three-argument form issues a send(2) — use the
four-argument form on an unconnected datagram socket
(SOCK_DGRAM) to route each message to TO, which triggers
sendto(2) under the hood. FLAGS is the bitmask the
system call accepts (commonly 0; see your platform’s send(2)
man page for MSG_DONTWAIT, MSG_OOB, MSG_NOSIGNAL, and friends).
Synopsis#
send SOCKET, MSG, FLAGS, TO
send SOCKET, MSG, FLAGS
What you get back#
The number of bytes accepted by the kernel, or undef
on error with $! set. Always check the return value:
my $n = send $sock, $buf, 0
or die "send failed: $!";
Two properties bite people:
The count is bytes, not characters.
length $bufon a wide string and the returned count will not agree.On
SOCK_STREAMsockets the kernel may accept fewer bytes than you gave it — a short write. Loop until the whole buffer is drained, or usesyswritewhich has the same short-write semantics but works on any filehandle.
Global state it touches#
$!— set to the system error on failure.The socket’s PerlIO layer stack is not consulted. Output layers (
:utf8,:encoding(...),:crlf) have no effect on whatsendwrites. In particular, a:utf8layer causessendto throw an exception rather than silently encode — the socket layer and the PerlIO layer cannot both own byte framing.
Examples#
Connected TCP — three-argument form:
use Socket;
socket my $sock, PF_INET, SOCK_STREAM, getprotobyname("tcp")
or die "socket: $!";
connect $sock, sockaddr_in(80, inet_aton("example.com"))
or die "connect: $!";
send $sock, "GET / HTTP/1.0\r\n\r\n", 0
or die "send: $!";
Unconnected UDP — four-argument form with an explicit destination:
use Socket;
socket my $sock, PF_INET, SOCK_DGRAM, getprotobyname("udp")
or die "socket: $!";
my $to = sockaddr_in(514, inet_aton("10.0.0.1"));
send $sock, "<14>hello syslog\n", 0, $to
or die "send: $!";
Handle short writes on a stream socket:
my $offset = 0;
while ($offset < length $buf) {
my $n = send $sock, substr($buf, $offset), 0;
defined $n or die "send: $!";
$offset += $n;
}
Send with a flag — MSG_DONTWAIT makes a single non-blocking
attempt and returns undef with $! set to
EAGAIN/EWOULDBLOCK if the kernel buffer is full:
use Socket qw(MSG_DONTWAIT);
my $n = send $sock, $buf, MSG_DONTWAIT;
if (!defined $n) {
if ($!{EAGAIN} || $!{EWOULDBLOCK}) {
# back off, retry later
} else {
die "send: $!";
}
}
Edge cases#
Wide characters: passing a string with codepoints above
0xFFon a byte socket writes the UTF-8 encoding of each character and emits aWide character in sendwarning underuse warnings. Encode explicitly withEncode::encodebefore callingsend.:utf8layer on the socket:sendcroaks. Either open the socket without the layer, or callbinmode$sockto strip it before the firstsend. An:encoding(...)layer implicitly adds:utf8, so it’s banned too.Four-arg form on a connected socket: passing
TOto a connectedSOCK_STREAMsocket is an error — the kernel returnsEISCONN. Use the three-argument form once connected.Three-arg form on an unconnected datagram socket: fails with
ENOTCONN(orEDESTADDRREQon some platforms). Eitherconnectthe datagram socket first (which pins a default peer), or supplyTO.Empty
MSGon UDP: valid — sends a zero-length datagram the peer can read withrecv. On TCP it is a no-op that returns0.SIGPIPEon a closed stream peer: writing to aSOCK_STREAMwhose remote end has closed raisesSIGPIPE, which by default terminates the process. PassMSG_NOSIGNALinFLAGS(Linux) or install$SIG{PIPE} = 'IGNORE'to get anEPIPEreturn instead.sendmsg(2): Perl exposessend/sendto, notsendmsg. Scatter/gather writes and ancillary data (credentials, file descriptors overAF_UNIX) require an XS module such asSocket::MsgHdr.Non-socket filehandle:
sendon a non-socket returnsundefwith$!set toENOTSOCK. Usesyswritefor pipes and regular files.
Differences from upstream#
Fully compatible with upstream Perl 5.42.
See also#
recv— the inverse; reads bytes from a socket with the same layer restrictions and the sameFLAGSargumentsyswrite— raw write that bypasses PerlIO buffering on any filehandle; use it for pipes and files wheresendrefuses to workconnect— establishes the peer address that lets you use the three-argument form ofsendsocket— creates the filehandlesendwrites to; the socket type (SOCK_STREAMvsSOCK_DGRAM) decides which form ofsendis legalbind— assigns a local address; needed beforesendon a datagram socket if the peer expects replies to a known portbinmode— strips a stray:utf8layer that would otherwise makesendthrow