Unix Domain Socket Datagrams Madness
April 1st, 2008
Unix domain sockets can be a bit fiddly. Here are some mistakes I made:
- for datagrams, use recvfrom and sendto. There is no need to do the listen, accept or connect calls for datagrams. Just bind().
- make sure when you call recvfrom, you initialise the fromlen value to be the size of the sockaddr_un struct otherwise it will get confused as to how much space it has to populate the struct and weird things
mightwill happen. - When using the unix abstract address space (rather than the filesystem), the first byte of sun_path should be a ‘\0’. But you need to get the length of the string before you clear the first char so that you can pass the true size of the struct to the bind() call. See ‘man 7 unix’.
- I found this example code very helpful (although it uses the filesystem, not the abstract address thing).
This is a short post but it represents more than two days of insanity.
[tags]ipc, linux, programming, unix sockets[/tags]