Skip to main content

Ports and Sockets

When an app wants to listen on a port, it calls an OS function. This native function adds an entry to a table. The table maps the port number to a callback in the app. The kernel calls it when data arrives on that port.

Port

It's a network property, but only logical. The network driver opens the TCP-IP packets up to layer 4. It then reads the destination IP and port.

Server Socket

This is the object that lets the server app hook into the port. Think of a socket like a power socket. Any appliance must plug in to get power.

When the kernel sees data for a thread, it wakes the thread. That thread was asleep on a file descriptor. The app then runs again. It accepts the connection and returns a socket object.

This is an infinite loop which will be polling/waiting for new connections.

Socket is like pipe

This socket carries data between source and destination for the whole session. Many messages can use the same socket,

Socket

This is the actual object that's used by the application to read and send data back.

The acceptor thread then hands the task to a worker thread. The worker processes the data from the socket.

Port and Sockets

Port is just logical.

A socket is just a C object. It reads data from a buffer and writes the response back to a buffer.

Ports and sockets
port is virtual and socket is virtual representation of the physical connection

Port is a network property. Note that it's only virtual. The operating system just binds the requested port to the process. The port accepts connections when the kernel's network stack sees a packet for it.

A socket is how a network connection is shown in software. The best way to put it: a UNIX socket is a data structure in code to send or receive data. It has two queue fields. One for incoming data, one for outgoing.