Skip to content

Instantly share code, notes, and snippets.

@ryran
Created March 3, 2016 22:45
Show Gist options
  • Save ryran/170009f84c11bf3243b1 to your computer and use it in GitHub Desktop.
Save ryran/170009f84c11bf3243b1 to your computer and use it in GitHub Desktop.
tiny C application to create a unix socket (UDS) file
#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;
}
@ryran
Copy link
Author

ryran commented Mar 3, 2016

Compile and use:

~]# 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

@nasr-edine
Copy link

thanks for this code

@typelogic
Copy link

Thanks. You might want to check retval of bind because a pre-existing file or even ordinary file is fatal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment