This article is from the Firewalls FAQ, by Matt Curtin cmcurtin@interhack.net and Marcus J. Ranum mjr@nfr.com with numerous contributions by others.
by Mikael Olsson
This appendix will begin at a fairly ``basic'' level, so even if the first
points seem childishly self-evident to you, you might still learn something
from skipping ahead to something later in the text.
C.1 What is a port?
A ``port'' is ``virtual slot'' in your TCP and UDP stack that is used to
map a connection between two hosts, and also between the TCP/UDP layer and
the actual applications running on the hosts.
They are numbered 0-65535, with the range 0-1023 being marked as
``reserved'' or ``privlileged'', and the rest (1024-65535) as ``dynamic'' or
``unprivileged''.
There are basically two uses for ports:
* ``Listening'' on a port.
This is used by server applications waiting for users to connect, to
get to some ``well known service'', for instance HTTP (TCP port 80),
Telnet (TCP port 21), DNS (UDP and sometimes TCP port 53).
* Opening a ``dynamic'' port.
Both sides of a TCP connection need to be identified by IP addresses
and port numbers. Hence, when you want to ``connect'' to a server
process, your end of the communications channel also needs a ``port''.
This is done by choosing a port above 1024 on your machine that is not
currently in use by another communications channel, and using it as the
``sender'' in the new connection.
Dynamic ports may also be used as ``listening'' ports in some applications,
most notably FTP.
Ports in the range 0-1023 are almost always server ports. Ports in the range
1024-65535 are usually dynamic ports (i.e., opened dynamically when you
connect to a server port). However, any port may be used as a server port,
and any port may be used as an ``outgoing'' port.
So, to sum it up, here's what happens in a basic connection:
* At some point in time, a server application on host 1.2.3.4 decides to
``listen'' at port 80 (HTTP) for new connections.
* You (5.6.7.8) want to surf to 1.2.3.4, port 80, and your browser issues
a connect call to it.
* The connect call, realising that it doesn't yet have local port number,
goes hunting for one. The local port number is necessary since when the
replies come back some time in the future, your TCP/IP stack will have
to know to what application to pass the reply. It does this by
remembering what application uses which local port number. (This is
grossly simplified, no flames from programmers, please.)
* Your TCP stack finds an unused dynamic port, usually somewhere above
1024. Let's assume that it finds 1029.
* Your first packet is then sent, from your local IP, 5.6.7.8, port 1029,
to 1.2.3.4, port 80.
* The server responds with a packet from 1.2.3.4, port 80, to you,
5.6.7.8, port 1029.
* This procedure is actually longer than this, read on for a more
in-depth explanation of TCP connect sequences.
 
Continue to: