O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

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

Using UNIX Domain Sockets

Problem

You want to communicate with other processes on only the local machine.

Solution

Use domain sockets. You can use the code and techniques from the preceding Internet domain recipes, with the following changes:

  • Because the naming system is different, use sockaddr_un instead of sockaddr_in.

  • Use IO::Socket::UNIX instead of IO::Socket::INET.

  • Use PF_UNIX instead of PF_INET, and give PF_UNSPEC as the last argument to socket.

  • SOCK_STREAM clients don’t have to bind to a local address before they connect.

Discussion

Unix domain sockets have names like files on the filesystem. In fact, most systems implement them as special files; that’s what Perl’s -S filetest operator looks for—whether the file is a Unix domain socket.

Supply the filename as the Peer argument to IO::Socket::UNIX->new, or encode it with sockaddr_un and pass it to connect. Here’s how to make server and client Unix domain datagram sockets with IO::Socket::UNIX:

use IO::Socket;

unlink "/tmp/mysock";
$server = IO::Socket::UNIX->new(LocalAddr => "/tmp/mysock",
                                Type      => SOCK_DGRAM,
                                Listen    => 5 )
    or die $@;

$client = IO::Socket::UNIX->new(PeerAddr  => "/tmp/mysock",
                                Type      => SOCK_DGRAM,
                                Timeout   => 10 )
    or die $@;

Here’s how to use the traditional functions to make stream sockets:

use Socket; socket(SERVER, PF_UNIX, SOCK_STREAM, 0); unlink "/tmp/mysock"; bind(SERVER, sockaddr_un("/tmp/mysock")) or die "Can't create server: $!"; socket(CLIENT, PF_UNIX, SOCK_STREAM, 0); connect(CLIENT, sockaddr_un("/tmp/mysock")) ...

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