example to explain unix domain socket - AF_INET vs

2019-03-09 20:32发布

问题:

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.

回答1:

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.



回答2:

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)