Is there a command similar to mkfifo but for domain sockets?
5 Answers
There is no exact equivalent of mkfifo for socket, i.e. there is no command that just creates a "hanging" socket. This is for historical reason: server's function bind(), the one that creates a socket name/inode in the filesystem, fails if the name is already used. In other words, server cannot operate on a pre-existing socket.
So if you'd created socket earlier, it would need to be removed by the server anyway first. No benefit. As you see with Gregory's answer, you can create a socket IF you keep a server for it, such as netcat. Once a server is gone, the old socket is gone. A new server has a new socket, and all clients need to re-connect, despite the socket's name being identical.
- 14,252
You can use python:
python -c "import socket as s; sock = s.socket(s.AF_UNIX); sock.bind('/tmp/test.sock')"
Also C, see this answer.
- 1,247
Most recent netcat (nc) and similar programs (socat as far as I know) have domain socket options.
Else, you can have a look at ucspi-unix
- 1,775
On Linux, it's very simple to create such a program:
#include <sys/stat.h>
#include <stdio.h>
int main(int C, char **V){
int r=0; while(*++V) if (mknod(*V,S_IFSOCK|0666,0)) r=1,perror(*V);
return r;
}
mknod on Linux can also make all the other filetypes as per the given S_IF... argument there.
On other UNIXES, I'm afraid you need to do the rather complicated dance of allocating a socket file, binding it and dropping the descriptor:
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main(int C, char **V){
int r=0; while(*++V){
int sfd = socket(AF_UNIX,SOCK_DGRAM,0);
if (0>sfd){ perror("socket"); goto fail; }
struct sockaddr_un a; a.sun_family = AF_UNIX;
size_t len = strlen(*V);
if (len+1 > sizeof(a.sun_path)){ errno=ENAMETOOLONG, perror("bind"); goto close_and_fail; }
memcpy(a.sun_path,*V,len+1);
socklen_t socklen = (socklen_t)(len+1+offsetof(struct sockaddr_un,sun_path));
if (0>bind(sfd,(void*)&a,socklen)) perror("bind");
else{ close(sfd); continue; }
close_and_fail:
close(sfd);
fail: r=1;
}
return r;
}
As has been said, though, creating such orphaned socket files is not very useful. It definitely won't be usable as a socket address (a new wannabe server for that socketfile will need to unlink it first), but it will test (test -S file / [ -S file ] as a file of type socket, which might be usable in some scripts.
- 156