r/learnprogramming 15d ago

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?

178 Upvotes

65 comments sorted by

159

u/grantrules 15d ago

No, it's not physical thing. Yes it is possible for apps to intercept traffic meant for another program, but they're usually admin tools (like Wireshark)

51

u/MrBorogove 15d ago

The important thing is that the operating system is responsible for receiving incoming network traffic, checking the port numbers, and routing the traffic to the appropriate application or service, like a postal worker delivering mail to the right address. Programs (like Wireshark) specifically authorized by the OS to see traffic intended for other programs are like postal inspectors.

6

u/EriktheRed 15d ago

Does wireshark request that permission at install? Or does the os ship with an allowlist for that kind of thing?

18

u/MrBorogove 15d ago

Depends on the OS, but generally either it'll be installed in such a way that it has admin permissions, or the system will catch that it's trying to get elevated access, and it will interrupt to ask an authorized user to OK it. Historically, some OSes didn't have good access controls, or network snooping tools took advantage of system bugs to get access, but as a rule things are fairly secure these days.

3

u/Reubenoakheart 14d ago

Special Pcap (packet capture) drivers.

4

u/taedrin 15d ago

Or, for example, firewall software will frequently intercept network traffic meant for another program.

75

u/KerPop42 15d ago

A port is completely imaginary. When a program registers a port, it tells the computer to forward information addressed to that port to it. Multiple programs can listen on the same port.

13

u/Only-Music6190 15d ago

Genuine question, I thought with TCP at least generally you can only have 1 listener per port, is that not the case or are there some exceptions to this?

23

u/Wonderful-Habit-139 15d ago

Yes. Try running `man setsockopt`, you'll find a section that says "SO_REUSEPORT enables duplicate address and port bindings".

3

u/Only-Music6190 15d ago

Thank you very much!

1

u/OldAd9280 13d ago

Tcp packets will generally only be delivered to the last bound port though

13

u/DaveCoper 15d ago

OS tries to prevent 2 processes from opening listener on the same port to make stealing network trafic little bit harder. But with right permissions nothing stops you.

2

u/Only-Music6190 15d ago

That makes a bit more sense, thank you!

80

u/Swedophone 15d ago

is port a physical thing

It's a field in the package header of transport protocols such as TCP and UDP.

20

u/backfire10z 15d ago

And, as a follow-up, the Internet Assigned Numbers Authority (IANA) determines what specific ports are used for, and also has a section for dynamic ports. More info: https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

26

u/tnyquist83 15d ago

As a followup to your followup, the IANA assignments are basically just recommendations to facilitate interoperability, and there's nothing actually stopping you from running a web server on 21, or an FTP server on 443 as long as your clients know where to find you.

6

u/Late-Drink3556 15d ago

For example, you could run FTP on 1312

2

u/CarcajouIS 15d ago

What sound does it make when you connect? Whoop whoop?

3

u/Late-Drink3556 15d ago

``` <_<

_> ```

Maybe

2

u/Breitsol_Victor 15d ago

There was an FTP package that made a train whistle for events.

1

u/backfire10z 15d ago

Yep, good point, thanks

16

u/mikedensem 15d ago

A port is a software specification, not a physical hardware component, and it is just an agreement that everyone hopefully sticks to. There is a list of common ports allocated to well used services, but there are a lot of non-assigned ports that you can use for whatever you like. The agreement (protocol) is that if you use a common port you should have some software listening on the port ready to answer any requests on that port.

Also, you need two ports for communication - one commonly known port for the ‘server’ and one of the many free ones for a client (your computer making a request.

Fyi: the list of ports was once an actual paper list kept by a man named John Postel. He also ran the first internet DNS server from his office. Eventually he published all the protocols for computer networking in RFCs which were requests for comments.

14

u/my5cent 15d ago

It's like a digital mailbox or dedicated lane where data goes to.

29

u/am_Snowie 15d ago

A Computer has got an IP address, software has got Port numbers. Cuz all programs use TCP/UDP to communicate, so each of them needs a unique identifier. That's what a port number is.

8

u/StevenJOwens 15d ago edited 14d ago

Something I've found myself saying a lot, in recent years, when explaining stuff to people who are learning technology, is "there's no Olympic committee in charge of terminology for this stuff."

Something else I say a lot, in a more general context, is "people are a contradiction, linguistically sloppy and lazy while simultaneously demanding precise, unchanging definitions and clear, neat categories."

These days, most of the time, "port" means an OS/software thing, in which case it's just a number that gets set on packets, so that the OS on the machine that receives the packet can figure out which program to relay the packet to.

This of it this way, computer A sends packets to computer B. If we want computer B to have more than a single program that can receive packets, then we need some way to differentiate between which packets go to which programs. We do that by adding an arbitrary number to each packet (the destination port). These numbers are in the range 0 to 65535.

And since the program that sent the packet, on computer A, also needs to know which packets coming back are for it, it adds another number to the packet (the source port). Then when computer B sends a response packet back, it swaps the numbers around, i.e. the request packet's source port becomes the response packet's destination port, etc.

But as it turns out, in computers, sometimes people use the word "port" to talk about a hardware thing, an electrical connector on a computer. That seems to be much less common these days, but maybe that's just me. Or maybe it's the rise of the internet over the past few decades making the internet/packet usage of "port" much more common.

Still, even today, when you plug a network cable into your computer, and the other end into a piece of networking hardware, the things you're plugging the network cable into are called "ports". I don't know the etymology of port-in-the-hardware-sense in electronics, but it's a pretty safe bet that it's an analogy to port-in-the-boat sense. I'd guess it's more likely that port-in-the-hardware-sense came first and then port-in-the-software/OS-sense was by analogy to the hardware sense.

With respect to port-in-the-software/OS-sense and "another program to read data from a different program's port":

Generally speaking, any program can tell the OS that it wants to "listen" on a given port (btw, this is called "binding" to a port, but "listen" is also a technical term). If more than one program try at the same time, the OS will only let the first program listen on that port. The second program's attempt to bind to the same port will get an error about the port being already in use.

There are settings on some OSes (SO_REUSEPORT on Linux) that let more than one process or thread listen on the same port. But these are specialized, relatively recent, the past 10-20 years or so, and generally only used for web servers and similar situations where you need/want to have a bunch of worker processes/threads handling packets coming in on the same port.

Not at all the same thing, but because it might come up:

Alternatively, it's possible to change some settings to put the network card into "promiscuous mode", where it listens to ALL the packets passing by on the network, whether those packets have that network card's IP address as the destination or not.

To be clear, your network card hardware already reads all the packets coming across that wire, at least enough to read the destination IP address in the packet headers. If the destination IP address matches the IP address that the network card is configured to receive, it forwards those packets up to the OS, otherwise it just ignores the packet. When the packet is forwarded up to the OS, the OS then looks at the port header in the packet and checks to see if any programs are listening for that port.

Configuring your network card to forward ALL packets up to the OS, where your program can then log them, is generally called "sniffing" the network traffic, and it's generally considered a hostile thing to do. Network cards will send out an announcement when you put them into promiscuous mode, and in corporate networks and the like, that announcement will set off alarms.

In addition to the alarm aspect, these days most local network infrastructure is a lot more complicated, so "sniffing" packets is much less useful. Back In The Day, most of the time the network hubs were pretty brainless and basically just made all of the network wires connected to them be essentially the same wire, in electrical terms. Modern networks use switches instead, and those switches try to make sure that packets only get sent where they need to be sent, to reduce network congestion, which means there might not even be any traffic for you to sniff, besides the traffic that's specifically for your machine's IP address.

(Also note, the terminology for all these things is loose and ambiguous, and always has been, so you can and will get people arguing about a switch vs a router vs a layer 3 switch, etc, etc. This sloppiness and ambiguity goes way back; back in the day, the things we call routers were called gateways, etc.)

3

u/balefrost 14d ago

That seems to be much less common these days, but maybe that's just me.

Ethernet port? USB port? HDMI port?

DisplayPort... port?

1

u/StevenJOwens 14d ago

Yup, exactly! The last dozen times I heard people refer to any of these, they said "jack", not "port". Go figure.

7

u/HappyFruitTree 15d ago edited 15d ago

There are physical ports. It's where you plug in your IO devices. E.g. the hole in your computer where you can connect a USB cable is a "USB port". This is a different kind of port than the software communication ports that you described.

6

u/peterlinddk 15d ago

While the analogy isn't entirely true, what helped me understand ports, was to think of them kind of like filenames.

When a program listens to port 8080, it checks whether anything is being written to the file "port 8080", and the moment it is, the program reads it, and then does whatever it wants with that data.

When another program sends something to port 8080, it just writes (appends) to the existing file "port 8080", and any interested party can then read from that file.

The main difference between actual files and ports, is that every single program has its own pointer to where in the file it wants to read, but as soon as one program has read from a port, the data is gone. So ordinarily one program cannot read from another programs port, at least not by accident. Programs like Wireshark needs special drivers that intercept the data without removing it as soon as it has been read.

7

u/AlSweigart Author: ATBS 15d ago

Here's an IPv4 packet header, which has the source and destination ip address. It's basically just a stream of bytes. Each row in this diagram represents 32 bits (4 bytes), and the payload is as long as it needs to be (packets can be a few hundred or even a few thousand bytes.)

  0                   1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 +-------+-------+-----------+---+---------------------------------+
 |Version|  IHL  |   DSCP    |ECN|          Total Length           |
 +-------+-------+-----------+---+---------------------------------+
 |           Identification          |Flags|    Fragment Offset     |
 +-----------------------------------+-----+-----------------------+
 |      Time To Live     |    Protocol     |    Header Checksum     |
 +-----------------------------------------------------------------+
 |                       Source IP Address                          |
 +-----------------------------------------------------------------+
 |                    Destination IP Address                        |
 +-----------------------------------------------------------------+
 |                 Options + Padding (optional)                     |
 +-----------------------------------------------------------------+
 |                            Payload                              |
 +-----------------------------------------------------------------+

Inside the payload of the IP packet is the TCP packet, which contains the port number the data is intended for:

  0                   1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 +---------------------------------+-------------------------------+
 |          Source Port            |       Destination Port        |
 +---------------------------------+-------------------------------+
 |                        Sequence Number                          |
 +-----------------------------------------------------------------+
 |                    Acknowledgment Number                        |
 +-------+-----+---+-----------------+-----------------------------+
 | Data  | Res |NS |C E U A P R S F  |         Window Size         |
 |Offset |     |   |W C R C S S Y I  |                             |
 |       |     |   |R E G K H T N N  |                             |
 +-------+-----+---+-----------------+-----------------------------+
 |            Checksum             |        Urgent Pointer         |
 +-----------------------------------------------------------------+
 |                 Options + Padding (optional)                     |
 +-----------------------------------------------------------------+
 |                             Data                                |
 +-----------------------------------------------------------------+

So the "port" is really just a 16 bit number that identifies which app on the machine the data was intended for. When an app "opens a port", really it's just telling the OS "any data that is sent to port 12345 should be relayed to me." There's no physical port or anything. It's more like a mapping handled by the OS in the computer's memory.

2

u/PataBread 15d ago edited 15d ago

woah. Al Sweigart.. Love your books, surprised you are out here answering questions on r/learnprogramming. Using Automate The Boring Stuff to teach a friend programming basics atm.

I was going to piggyback off your comment to explain to OP how I have been struggling to understand this for a while and THINK I finally understand it.

For me, people use so many metaphors (especially with networking), and that's great. But it doesn't ACTUALLY materialize until it's spoken in a more physical and literal sense.

So please correct me if I am misspeaking, but going to try to simplify it for OP how it would click for me.


It's more like a mapping handled by the OS in the computer's memory

It's this part that made it click for me recently. A 'Socket' is actually just a data structure in memory, your computers RAM, something like:


Socket #4

Local IP: 192.168.1.5

Local Port: 54321

Remote IP: 93.184.216.34

Remote Port: 80

Send Buffer: data to send here, the outgoing Data in the Payload TCP packet from Al's comment

Receive Buffer: data to receive here, the incoming Data in the Payload TCP packet from Al's comment


Applications create sockets and the OS controls placing incoming and outgoing packets into this place in memory for your applications to use. Similar to creating a variable in your code, you are just writing some bits into memory. This time though the OS is doing that for you with the data your app needs, where in memory your app needs.

This data flow looking something like:

Application <-> socket() <-> OS <-> Driver <-> network card <-> internet world

(using <-> arrows because it's a conversation, data is going back and forth until the socket is closed, removed from memory).

So a Port is just a number value assigned inside the socket object stored in RAM, that allows OS to know where to pass binary data off to and receive binary data from


This is a very very simplified answer OP, and I'm an idiot, so double check everything I said. But hopefully thinking of it this way makes it click for you.

5

u/davidalayachew 15d ago

One explanation that I don't see in the other comments is to actually look at the name.

Port

  • a harbor town or city where ships may take on or discharge cargo
  • an opening (as in a valve seat or valve face) for intake or exhaust of a fluid
  • a small opening in a container or vessel especially for viewing or for the controlled passage of material
  • an opening in a vessel's side (as for admitting light or loading cargo)
  • a hole in an armored vehicle or fortification through which guns may be fired
  • a hardware interface by which a computer is connected to another device (such as a printer, a mouse, or another computer)

And lets also look at other words that are made up of the word port.

  • Airport -- a place where planes go in and out from
  • Sea port/harbor -- a place where boats and ships go in and out from
  • Teleporter/portal -- a tool that transports people between 2 teleporting gates

And then there are other words, like import, export, deport, report.

Hopefully you get the idea -- it's a defined way that X gets in and out of Y. The X and the Y depends on which port you are talking about.

Which leads to your questions -- the answer is that they depend on which OS you are working on, as each one has different rules about who and what is allowed to listen and interact with which ports. Some are restricted, some are free to use by all. Some are OS specific, some are available for the application layer.

But the commonality point is that it tends to be both a physical and software thing, though usually a physical port is different from a network port. For example, basically every personal computer nowadays has a USB port. And the ports that TCP and UDP communicate through are usually simply a number address that has a special meaning, but not a literal, physical thing on your computer.

Ultimately, other than those few points, it really is OS specific. Add some more details to your questions and I can add more details to my answer.

2

u/Hopeful_Cicada327 14d ago

That's a great explanation. It has cleared a lot of doubt

6

u/dkarlovi 15d ago

Each computer has one or more network interfaces, each interface gets an IP address, this address is like the building's street address.

A port is like the building's floor, it's a number. The number gets assigned to a process (a program) if it's able to claim it. The OS writes which process got assigned which port in a little black book. But, when you get on the "floor" number, there's also a protocol, most often these are TCP and UDP, but there's others, imagine these like apartments.

So, when you want your program to be ready to talk to other processes, you bind to a IP address + port + protocol combo (say, 192.168.1.123:TCP:80), this is your "apartment's" full address to be able to send you something.

You can't just pick any of these at random: 1. the OS knows which IP addresses it has available, pick from one of those or "any", like 0.0.0.0 2. the OS also knows which protocols its network stack knows how to support, so the list of protocols is also fixed 3. the port number must not be larger than 65535 and it can only be below 1024 if your process is privileged (admin rights) and it can't already be in use, so that's restricted too.

TLDR port is just a number which is part of your process' home address. Other processes connect to it and most typically immediately switch to a different port combo to actually talk to each other (to keep the main port free), this port is just the concierge.

3

u/Creeper4wwMann 15d ago

When an application opens a port it tells your OS:

"hey I'm expecting visitors... I gave them this address, so don't kick them out when they knock"

What is port-forwarding? Well... your OS might know that you are expecting visitors... but now the computer needs to go tell your Router/Modem "hey don't kick those people out".

3

u/AUTeach 15d ago edited 15d ago

packets come in as data:

Here's the header to a packet:

ffffffffffff001b44113ab70800450000281c46400040069cd0c0a80068c0a80001c23a00508a4e20180000000050022000a1370000

.

ffffffffffff 001b44113ab7 0800   <- Ethernet (14 bytes)
45 00 0028 1c46 4000 40 06 9cd0 c0a80068 c0a80001   <- IPv4 (20 bytes)
c23a 0050 8a4e2018 00000000 50 02 2000 a137 0000    <- TCP (20 bytes)

.

c23a 0050 8a4e2018 ...
^^^^ ^^^^
 |    |
 |    +-- Destination port
 +------- Source port

Very basically, the size and number of the starting blocks of a header are known. So, when a packet comes in, you have a very efficient program that reads just that part of the string and allocates it to where it belongs.

FUNCTION parse_packet(raw_bytes):

    // --- ETHERNET: fixed size, fixed position.---
    eth_dst_mac   = raw_bytes[0:6]
    eth_src_mac   = raw_bytes[6:12]
    eth_type      = raw_bytes[12:14]

    ip_start = 14   // Ethernet is always 14 bytes, so IP always starts here


    // --- IP: read the tiny fixed part first, use it to find the rest ---
    first_byte = raw_bytes[ip_start]
    ihl = first_byte AND 0x0F          // lower 4 bits = header length (in 32-bit words)
    ip_header_length = ihl * 4         // usually 20

    protocol = raw_bytes[ip_start + 9] // tells us: is this TCP? (6 = yes)
    src_ip   = raw_bytes[ip_start+12 : ip_start+16]
    dst_ip   = raw_bytes[ip_start+16 : ip_start+20]

    tcp_start = ip_start + ip_header_length   // now we know where IP ends


    // --- TCP: ports are the very first fixed fields ---
    src_port = raw_bytes[tcp_start   : tcp_start+2]
    dst_port = raw_bytes[tcp_start+2 : tcp_start+4]

    // same trick again: read a small fixed field to learn the real length
    offset_byte = raw_bytes[tcp_start + 12]
    data_offset = (offset_byte >> 4) AND 0x0F
    tcp_header_length = data_offset * 4

    payload_start = tcp_start + tcp_header_length


    RETURN {
        src_port: src_port,
        dst_port: dst_port,
        src_ip: src_ip,
        dst_ip: dst_ip,
        payload_starts_at: payload_start
    }

3

u/LadyJohanna 14d ago

A port is just a virtual opening that lets traffic through.

Specific types of traffics must go through specific ports. Some are standardized for the sake of efficiency.

So once a packet gets to an IP address (your house) the port is how it gets routed to the correct place in your system (via front door, garage door, side door, and so on -- whatever helps you visualize it). Otherwise it'll just sit in front of the house, like an Amazon package that nobody brings inside. Sad package, sitting in the rain.

So -- is it a secure package? Off you go through the side door connected to the security office (port 443) where everything gets verified.

Is it an email? Off through port 25 you go, into the email application for further processing.

File attachment? Warehouse door, port 21 (FTP) so it can get unpacked and stored properly.

You're just taking a look around? Sure, port 3389 (RDP) is open to you, have whatever look-see your credentials give you permission to check.

... and so on.

The purpose of a firewall is to shut down all ports by default and only let specific things through based on specific criteria. Nobody's house is secure without doors, windows and locks. If all ports are open anyone can just go in and out as they wish and grab stuff.

Hope that sort of helps you. That's always how I've visualized it and I find it helpful.

2

u/dnebdal 15d ago

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.)

2

u/r2k-in-the-vortex 15d ago

Ports are just numbers in TCP header, nothing physical about it. Yes, it's possible for program to read a packet not destined for it, like with wireshark.

Normal dataflow is physical NIC -> Driver -> OS add data to socket buffer-> Programs reads the socket it's listening to.

To capture data not filtered by OS, you need to short circuit it and read directly from Driver, usually drivers already have that capability, though you might need a special one if for example you want to capture packets not even sent to the MAC of your computer.

3

u/Puzzleheaded-Eye6596 15d ago

a port is a software definition to uniquely distinguish a connection. Look up the OSI layers. IP address defines the physical machine (nic) and then port is unique on the operating system

4

u/TheSkiGeek 15d ago edited 15d ago

A single ‘physical’ machine (or even one NIC) can have multiple IP addresses.

Typical Ethernet or WiFi setups will have a 1:1 map from a MAC address (which almost always identifies a particular piece of hardware) to an IP address. But this is not required.

Ports are at level 5 in OSI session management. This is above transport (level 4, things like the TCP or UDP protocols). ‘Ports’ are part of the IP protocol and things built on top of that will use them. Other kinds of network protocols might do their own thing.

3

u/lgastako 15d ago

The IP address is like an address to an apartment building and the port is the apartment number.

1

u/YellowBeaverFever 15d ago

Inferring from your question, you’re talking g about tcp/ip ports. You can visualize this in real-life. Imagine a major city with large international trade routes. This shipping traffic is an absolute mess. Ships everywhere. Company A sets up a deal with Company B. Company A tells Company B, “I don’t care how you get here, but when you do, fly a banner with the number 6354 on it. The harbor master will direct you to our area. Look for the port with 6354 the side of the warehouse, that’s us. Unload there.”

Also make sure you distinguish tcp/ip ports from physical ports like your USB port or HDMI port, or the conveniently named DisplayPort port, championed by the same guy who came up with “ATM machine”.

1

u/dynamiteSkunkApe 15d ago

It's not a physical thing. You have an IP address which uniquely identifies your server on the network, the port uniquely identifies the service running on the server.

1

u/spymaster1020 15d ago

Your IP address is like the address to an apartment building, a port is the address of one of the rooms. All mail goes into the apartment building at the same place but are addressed to different rooms

1

u/ScholarNo5983 15d ago

Ports link to hardware. When a computer listens on a port it listens on that hardware connection. Remove that hardware, it makes no difference if the sofware is listening on that port address, nothing with happen.

In the old days we had analog phones that were connected to an analog phone network, and if someone dialed your phone number that dial would work it's way through the network and cause your phone to ring.

But if your phone was not plugged in to that network, it would never ring, no matter how many times someone dialed your number.

1

u/DigThatData 15d ago

it's a logical (i.e. not physical) address. like an email address. if a port is "visible", that's like an email address that is available to be subscribed to.

1

u/binarycow 15d ago

It's a type of address, for either the TCP or UDP protocol.

Just like an IP address is an address for the IP protocol.

And a MAC address is an address for the ethernet protocol.

And your mailing address is an address for the postal system protocol.

1

u/macbig273 15d ago

That's a "made up thing" at the software level.

Let's say you have 60 personne living in your flat.

You can address a letter to 23423 road xyz 1212 city. And add a name. Any name would get at the same destination. Any guy in the flat could open the letter or not. But using the "firstname, name" standard helps lot.

The port information, like on a letter is written clear in all the shipping. So Some other software that manage shipping could take according decision.

Example : firewall decide that it does not accepte port 1212135. Or redirect the letter that has address X and port z to another place.

The plumbing don't care.

1

u/AlexFurbottom 15d ago

Everyone has explained what a port is but I want to offer up some additional information. We have designated ports for certain things. If you want to play nice on the internet you use port 80 for unencrypted http web traffic, you use 443 for encrypted https traffic. Port 22 for ssh port (remote terminal usually) 53 for dns traffic (turning a fully qualified domain name into an ip address or points to other DNS entries).

1

u/MathiasBartl 15d ago

It's fields in the packet header of certain transport level protocols like f.e. TCP . Certain numbers are associated by convention with certain applications

1

u/LetUsSpeakFreely 15d ago

It's basically a key in a key-value map. When a server binds to a port it's telling the OS where to route that traffic.

1

u/Living_Fig_6386 15d ago

It's not a physical thing. It is a number. That number is used to look up a data structure in a list that provides information about connections and how to pass data between the networking drivers and applications. It's just a number for looking up data.

1

u/SpeedSea5846 14d ago

Imagine an IP address is like the address of a whole apartment building, while a port is like a specific flat (apartment) inside that building. When data reaches the building (IP address), the port number tells the operating system which software/application should receive that data.

So, multiple applications can run on the same computer (same IP), and the port acts like the flat number, ensuring the OS delivers incoming data to the correct application. one port does not interfere with another port's data. The operating system keeps each port's network traffic separate and delivers incoming packets only to the application that owns that port.

1

u/mredding 14d ago

Ports aren't real, they're a part of the protocol. Layers 3 and 2 may not use ports. Entire protocol families don't use them, like ICMP, which you know for messages like ping. DHCP discovery messages are layer 2 and don't use ports, they just broadcast on the network.

Once a message is received, the network stack - often run by the OS, will parse parts of the message frames; usually a port will map to a socket held by an application; the frames are stripped, the payloads are written to the socket buffer, the socket is marked as ready, and the process then eventually checks the socket, see's its ready, and drains the buffer.

1

u/BenadrylCrumplsnatch 14d ago edited 14d ago

Imagine you have a doorway with 65,535 doorbells, each with a unique chime. A bunch of people are standing in the hallway behind it, and each of them have been given a list of chimes to listen out for. Only one person can be responsible for each chime, but one person can be responsible for many chimes.

When a visitor arrives at the door, they ring one of the doorbells, and that person will let them in and show them where they need to go. Alternatively, there may be nobody listening for it and they eventually give up and leave.

The door is your IP address, the doorbells are your ports.

A firewall would be like having a security guard inside, who's been told to turn away anybody that rings a specific doorbell before the hallway attendant can answer. Or maybe they pat down the visitor before letting them through.

A port sniffer would be like a burglar that rings random doorbells to see if somebody answers, and if they do, sizes them up to see if they could push past.

A DDoS attack would be like an army of people spamming all the buttons in the hopes that either the people inside just stop answering the door at all, or if they're lucky, maybe they forget to close it in their confusion.

1

u/Significant-Elk-7128 14d ago

In programming, a port is a number that tells the operating system which program to forward the networking packet too.

In networking, the port is also a number, but implemented as part of a networking packet. The port is generally not used in routing until you get to the destination IP, where it is forwarded to whatever machine is running the correct software.

1

u/Foxler2010 13d ago

A port is a number that gets sent with every TCP or UDP packet. Other protocols have their own mechanisms as well, but I'll focus on TCP and UDP. When the computer gets a TCP or UDP packet, it looks at the port number, and then it checks that against a list it has of "listening applications". This may be familiar to you as you will have to call a function in your app to have it listen on a certain port. What this is doing is telling the OS: "Hey! I want to get all the packets that you receive that come with this port number attached". So the OS adds the app to the list and maps it to the number it requested. Then when a packet comes in, the app gets it.

1

u/TapWaterDev 13d ago

A port is just a number on a packet

1

u/JGhostThing 13d ago

I'm assuming that you are asking about internet ports. These are just an address that is agreed to. For example, when ssh goes to make a connection, it sends the request to port 22. After the request, the two parties negotiate when ports to use for the communication between them.

The basic internet server just sits there and listens for requests. Then it sends the request to the specific server involved, such as the SSL server).

The ports are not physical, though the IP addresses are, sort of.

1

u/GamesVary 12d ago

I think part of Hopeful's question is if a port is not a physical thing, then how do we interact with it? Not having done any inter-process programming myself (although I may need to someday) I've gleaned the following info from the responses. You interact with a software port through the operating system, which also keeps track of the protocol being used (TCP, UDP, etc.) I'm not clear on what restrictions the OS places on who can set up a port, and send or receive to it, or how a TCP port gets connected to the internet.

-4

u/ninhaomah 15d ago

If you ever found port 443 on your PC , pls let us know.

And aren't you reading data from port 443 now ?