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

  1. 1973 UNIX Before Unix sockets the primary method for processes to communicate was through pipes |. While powerful pipes were limited to one direction a | b (b can’t talk back to a). You can’t easily talk to a globally running, independent system daemon like a database usin g a pipe

  2. 1983 BSD DARPA 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_UNIX or AF_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, like io.Reader in Go where you must implement read(). 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 the file_operations interface implements.
    • main difference between these implementations is the construction, files use open() syscall while sockets use socket() (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_operations interface is basically a thin wrapper to those methods but they work and can be called or the underlying socket methods can be called.