Thursday, April 23, 2015

mksock command

I was disappointed to discover Mac OS X 10.9.5 lacks an mksock command, in order to create a Unix domain socket. Now, usually applications will create these as needed, yet sometimes it is useful to create one manually (such as for testing purposes.) So I wrote my own mksock command, code is below:

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

int main(int argc, char **argv) {
        if (argc < 2) {
                fprintf(stderr, "usage: mksock PATH...\n");
                return 1;
        struct sockaddr_un addr;
        int rc = 0;
        for (int i = 1; i < argc; i++) {
                memset(&addr, 0, sizeof(addr));
                addr.sun_family = AF_UNIX;
                strncpy(addr.sun_path, argv[i], sizeof(addr.sun_path));
                addr.sun_path[sizeof(addr.sun_path)-1] = 0;
                const int fd = socket(PF_UNIX, SOCK_STREAM, 0);
                if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) != 0) { 
                        fprintf(stderr, "mksock: %s: %s\n", addr.sun_path, strerror(errno));
                        rc = 1;
 return rc;