Linux named sockets howto

A Unix/Linux socket file is basically a two-way FIFO.  Since sockets were originally created as a way to manage network communications, it is possible to manipulate them using the send() and recv() system calls.  However, in the Unix spirit of “everything is a file”, you can also use write() and read().  You need to use socketpair() or socket() to create named sockets.  A tutorial for using sockets in C can be found here: Beej's Guide to Unix IPC: Unix Sockets.

The socat command line utility is useful when you want to play around with sockets without writing a "real" program.  It is similar to netcat and acts as an adapter between different networking and file interfaces.

Links:

  • socat project home
  • An introduction to socat
  • Interesting article about Unix sockets and socat

Create a socket quickly in python:

~]# python -c "import socket as s; sock = s.socket(s.AF_UNIX); sock.bind('/tmp/somesocket')"
~]# ll /tmp/somesocket 
srwxr-xr-x. 1 root root 0 Mar  3 19:30 /tmp/somesocket

Or with a tiny C program, e.g., save the following to create-a-socket.c:

#include <fcntl.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    // The following line expects the socket path to be first argument
    char * mysocketpath = argv[1];
    // Alternatively, you could comment that and set it statically:
    //char * mysocketpath = "/tmp/mysock";
    struct sockaddr_un namesock;
    int fd;
    namesock.sun_family = AF_UNIX;
    strncpy(namesock.sun_path, (char *)mysocketpath, sizeof(namesock.sun_path));
    fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    bind(fd, (struct sockaddr *) &namesock, sizeof(struct sockaddr_un));
    close(fd);
    return 0;
}

Then install gcc, compile it, and ta-da:

~]# gcc -o create-a-socket create-a-socket.c
~]# ./create-a-socket mysock
~]# ll mysock
srwxr-xr-x. 1 root root 0 Mar  3 17:45 mysock