Recipe 17.6 Using Unix Domain Sockets

17.6.1 Problem

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

17.6.2 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, and use Peer and Local instead of PeerAddr/PeerPort and LocalAddr/LocalPort.

  • 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.

17.6.3 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 forwhether 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 stream sockets with IO::Socket::UNIX:

use IO::Socket;

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

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

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

use Socket;

unlink "/tmp/mysock";
bind(SERVER, sockaddr_un("/tmp/mysock"))
    or die "Can't create server: $!";

connect(CLIENT, sockaddr_un("/tmp/mysock"))
    or die "Can't connect to /tmp/mysock: $!";

Unless you know what you're doing, set the protocol (the Proto argument to IO::Socket::UNIX->new and the last argument to socket) to 0 for PF_UNIX sockets. You can use both SOCK_DGRAM and SOCK_STREAM types of communication in the Unix domain, with the same semantics as we saw for Internet sockets. Changing the domain doesn't change the characteristics of the socket type.

Because many systems actually create a special file in the filesystem, you should delete the file before you try to bind the socket. Even though there is a race condition (somebody could create a file with the name of your socket between your calls to unlink and bind), this isn't a security problem, because bind won't overwrite an existing file.

17.6.4 See Also

Recipe 17.1 through Recipe 17.5