Sockets
Pithy
A socket is a communication endpoint exposed to your program as a file descriptor, with a protocol-specific implementation underneath and a thin wrapper arounds the file interface that lets generic read/write/close work on it.
History
1973 UNIXBefore Unix sockets the primary method for processes to communicate was through pipes|. While powerful pipes were limited to one directiona | b(bcan’t talk back toa). You can’t easily talk to a globally running, independent system daemon like a database usin g a pipe1983 BSDDARPA funds uc berkley to add TCP/IP networking to Unix. Bill Joy needed an API for this communication.They made berkley sockets, for both networking (e.g.,
AF_INET) and local IPC (e.g.,AF_UNIXorAF_LOCAL) under the same set of syscalls.This let programmeres use the same file like abstractions (
read(),write(),close()) for local and network communication.- The interface in C is:
file_operations, likeio.Readerin Go where you must implementread(). A socket is just one implementation that satisifies the interface along with regular files, pipes, devices. The kernel does the dynamic dispatch on the fd, calling the methods thefile_operationsinterface implements. - main difference between these implementations is the construction, files use
open()syscall while sockets usesocket()(plus some more plumbing) once created the implementation details fade away (somewhat) and you can focus on writing generic code that call the interface methods on the specifics of the underlying type. - the socket class (struct) has more methods and it’s implementation of the
file_operationsinterface is basically a thin wrapper to those methods but they work and can be called or the underlying socket methods can be called.
- The interface in C is: