example to explain unix domain socket - AF_INET vs AF_UNIX
AF_UNIX Sockets provide for great inter-process communication. Open a socket pair socketpair(..)" and bind to a temporary filename. Write to one of the pair arrives at the other. The kernel routes messages without protocol or filesystem overhead. One can use blocking i/o or select(...) to synchronize threads and processes in a FIFO manner. I like non-blocking with select and datagram (can get a length) mode but you can choose your own. Be sure to delete the temporary file on exit (it will have zero bytes but will still show up in the filesystem directory)
If you want to communicate with a remote host, then you will probably need an INET
socket.
The difference is that an INET
socket is bound to an IP address-port tuple, while a UNIX
socket is "bound" to a special file on your filesystem. Generally, only processes running on the same machine can communicate through the latter.
So, why would one use a UNIX
socket? Exactly for the reason above: communication between processes on the same host, being a lightweight alternative to an INET
socket via loopback.
In fact, INET
sockets sit at the top of a full TCP/IP stack, with traffic congestion algorithms, backoffs and the like to handle. A UNIX
socket doesn't have to deal with any of those problems, since everything is designed to be local to the machine, so its code is much simpler and the communication is faster. Granted, you will probably notice the difference only under heavy load, e.g. when reverse proxying an application server (Node.js, Tornado...) behind Nginx etc.