Networking – How do networking ports work? Can I configure the ports that client and server use

networkingporttcp

Let's say i have a "server" program listening on address 1.2.3.4:69 (i.e. remote port 69)

When i connect from a "client" program to it, typically i would specify the IP address + port of the target or server system;

But what port would the client be using ? And how does the server know which port to connect back to the client on?

I understand this question is very general, but just wanting to get a general feel for how things work.

Then extending this to a specific protocol, say FTP (typical port 21), can I change it such that the server uses port 69, but the client uses port 100?

And similarly, for Remote Desktop in WinXP (typical port 3389), i know how to change the server port to be something other than 3389, but how does one change what port the client uses (if at all possible)?

Best Answer

When i connect from a "client" program to it, typically i would specify the Ip address + port of the target or server system;

Yes, correct.

But what port would the client be using ?

The client usually uses a random port. More precisely: For TCP to work, the only requirement is that the combination of destination address, destination port, source address, source port is unique - because this is used to keep track of TCP connections. So in principle the OS could just increment the source port number for each new connection. Actually, many OSes used to do this, but it made certain kinds of attacks easier, because an attacker could predict the next port number. So most modern OSes now use random source ports.

And how does the server know which port to connect back to the client on?

A TCP packet contains both the destination and the source port, so each side knows both port numbers. See e.g. the diagram for the data inside a TCP packet on http://en.wikipedia.org/wiki/Transmission_Control_Protocol .

Then extending this to a specific protocol, say Ftp (typical port 21), can i change it such that the server uses port 69, but the client uses port 100?

Usually you can configure a server to use any port you choose (though this depends on the individual server application). So you could configure the FTP server to use port 69. The client port cannot be configured as far as I know. The same goes for any other protocol such as RDP.

At any rate, why would you want to change the client port?