O'Reilly logo

Advanced Perl Programming by Sriram Srinivasan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Socket API and IO::Socket

Perl provides native support for sockets and a module called Socket to smooth some of the rough edges associated with the native socket call. It turns out that there are still a large number of options to deal with, and since most applications use a fairly standard set of options, we instead use a truly convenient module called IO::Socket, which is built on Socket.

This section uses this module to build a sending and receiving program.

Receiver

Just as you would ask the phone company for a telephone number and a physical handset, both sender and receiver ask the module to create sockets. Sockets, like telephones, are bidirectional endpoints: once a connection is established, either side can send and receive data, as long as there is an understanding between the two programs about the direction of communication.

Because only the receiving side needs to have a well-known address, we create a receiving socket as follows:

use IO::Socket;
$sock = new IO::Socket::INET (LocalHost => 'goldengate',
                              LocalPort => 1200,
                              Proto     => 'tcp',
                              Listen    => 5,
                              Reuse     => 1,
                             );
die "Could not connect: $!" unless $sock;

The IO::Socket::INET module provides a nice wrapper for Internet domain sockets. The LocalHost and LocalPort parameters specify the host and port on which this socket is going to listen. The number 1200 is chosen arbitrarily, but you must make sure that it doesn’t conflict with the port number used by some other application on that machine (otherwise, you get an error ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required