Sockets and IO::Socket

A TCP client

A socket is a file handle connected to another program. IO::Socket::INET ships with Perl and turns the connection details into one constructor call.

use strict; use warnings; use IO::Socket::INET; my $sock = IO::Socket::INET->new( PeerHost => "example.com", PeerPort => 80, Proto => "tcp", Timeout => 5, ) or die "connect failed: $!\n"; print $sock "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"; while (my $line = <$sock>) { print $line; } close $sock;

This is HTTP by hand: the request line, one header, a blank line, then the response. Reading until end of file works here because the server closes the connection after one response — with HTTP/1.1 you would have to parse the length header instead.

A TCP server

A server binds a local port and then calls accept in a loop. Each accepted socket is a separate conversation, so the server can keep listening while it talks to a client.

my $server = IO::Socket::INET->new( LocalAddr => "127.0.0.1", LocalPort => 9000, Proto => "tcp", Listen => 5, Reuse => 1, ) or die "cannot listen on 9000: $!\n"; print "listening on 127.0.0.1:9000\n"; while (my $client = $server->accept) { $client->autoflush(1); print "client connected from ", $client->peerhost, "\n"; while (my $line = <$client>) { chomp $line; print $client "echo: $line\n"; last if $line eq "quit"; } close $client; }

The block is the body of a server script: with the use lines of the client above it is a complete program, and it keeps serving until you stop it.

Reuse => 1 lets you restart the server without waiting for the old port to leave the TIME_WAIT state. autoflush matters: without it the reply may sit in a buffer while the client waits forever.

This server handles one client at a time. For several at once, accept and then fork, or use a module that does the event loop for you, such as IO::Socket::INET plus IO::Select, or a framework like Mojo.

Timeouts with IO::Select

Reading from a socket blocks until data arrives. If the other side goes silent, your program waits. IO::Select asks whether a handle is readable within a time limit:

use IO::Select; my $sel = IO::Select->new($sock); if ($sel->can_read(5)) { my $line = <$sock>; print "got: $line"; } else { warn "no answer in 5 seconds\n"; }

The same object can watch many sockets at once and return the readable ones, which is a compact way to write a server for a handful of clients. can_write works the same way for sending.

Framing and safety

TCP is a stream of bytes, not a sequence of messages. One write can arrive as two reads, and two writes can arrive as one. A protocol has to mark where a message ends.

The simplest framing is a newline after every message, which is what many line-based protocols do. For arbitrary binary data, prefix the payload with its length and read exactly that many bytes:

my $len = pack("N", length $payload); print $sock $len, $payload;

Switch such a handle to binary mode with binmode $sock, otherwise Perl may translate line endings on some systems and corrupt the bytes. On the reading side, use read in a loop until you have the announced count.

Bind to 127.0.0.1 while learning. Binding to 0.0.0.0 exposes the service to the network, and a small echo server without authentication is an open relay for anything that finds the port. Check peerhost only if you control the network: addresses are easy to spoof.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a socket in Perl?

    Answer

    A file handle connected to another program

    IO::Socket::INET returns a handle, and the ordinary read and print calls are the whole interface.

  2. What does Listen => 5 in the server constructor mean?

    Answer

    The kernel may queue five pending connections

    The number is the backlog of the listening socket, which holds the connections that are not accepted yet.

  3. Why does the server call autoflush(1) on the client socket?

    Answer

    So the reply is not left in a buffer while the client waits for it

    A buffered reply can sit in the process while the other side is blocked on a read.

  4. Why does TCP need framing?

    Answer

    Because it is a stream of bytes, so reads and writes do not line up with the messages

    One write can arrive as two reads and two writes as one, so the protocol has to mark where a message ends.

  5. What does the sender write in pack("N", length $payload)?

    Answer

    A four-byte big-endian number holding the length

    The receiver reads exactly four bytes, unpacks the count and then reads that many bytes of payload.

  6. Why bind to 127.0.0.1 while learning?

    Answer

    It keeps the service off the network, where anyone could reach an unauthenticated echo server

    The loopback address is reachable only from the same machine, and the page warns about the difference.

  7. What does this program print? my $payload = "abc"; my $len = pack("N", length $payload); print length($len), " ", unpack("N", $len), "\n";

    Answer

    4 3

    The packed length is four bytes, and unpacking it gives the three bytes of the payload back.

  8. What does this program print? use IO::Socket::INET; my $s = IO::Socket::INET->new( LocalAddr => "127.0.0.1", LocalPort => 0, Proto => "tcp", Listen => 5, Reuse => 1, ) or die "listen: $!"; print $s->sockport > 0 ? "listening\n" : "no\n";

    Answer

    listening

    Port 0 asks the system for a free port, and sockport returns the number it picked.

  9. What does this program print? my $buffer = "one\ntwo\nthr"; my @lines = split /\n/, $buffer; print scalar @lines, "\n";

    Answer

    3

    The split returns three pieces, the last of which is the partial line that has not ended yet.

  10. What does this program print? use IO::Socket::INET; my $s = IO::Socket::INET->new( PeerHost => "127.0.0.1", PeerPort => 1, Proto => "tcp", Timeout => 1, ); print $s ? "connected\n" : "refused\n";

    Answer

    refused

    Nothing listens on port 1, so the constructor returns false and the program takes the refused branch.

Article author: Arthur Isaev