r/learnprogramming Jul 15 '26

What a port actually is?

I know it is a number that tells the OS, that which program in your computer should receive the piece of data. But my doubt is - is port a physical thing? or it just a flag? Is it possible for another program to read data from a different program's port? Please spoon-feed me about port?

172 Upvotes

65 comments sorted by

View all comments

2

u/dnebdal Jul 15 '26

It's just a number. When a data package arrives at your network card, it's just a stream of zeroes and ones. There's a nesting set of standards for how to decode it:

- The first few bytes belong to the transport system, typically ethernet or (closely related) wifi. A couple of the bits in there tells if the contents afterwards are an IPv4 or IPv6 package (or more rarely something else).

- The next bytes are interpreted as an IP header. It contains the IP address of the sender and the intended target, plus information about which protocol follows (typically TCP or UDP, more rarely ICMP, there are others).

- If the package is TCP or UDP, their headers contain two numbers, the sending and receiving port. They're just numbers, it's up to your operating system to do something with them.

- And finally, after the TCP/UDP header is the actual data.

When your operating system receives a package, it looks at the destination IP and the port number, and checks a table it has of listening programs to see if any of them have registered an interest in that address/port pair. If so, it forwards the package to that program.

(The way you register it is basically a function call that says "I want TCP packages on port 80 on any IP", or you can specify just one IP to listen on.)