example to explain unix domain socket - AF_INET vs AF_UNIX

eagertoLearn picture eagertoLearn · Jan 9, 2014 · Viewed 29.7k times · Source

while I was reading for what AF_INET means, I learned that there is another family called UNIX domain socket. Here is the wiki link I read about this.

I do not understand what this means:

Unix domain sockets use the file system as their address name space. They are referenced by processes as inodes in the file system. This allows two processes to open the same socket in order to communicate. However, communication occurs entirely within the operating system kernel.

If I want to do SSH or FTP, what family do I use AF_INET or AF_UNIX. I am actually confused here a bit.

Answer

Stefano Sanfilippo picture Stefano Sanfilippo · Jan 9, 2014

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.