Search code examples
apachesocketstcpport

When using TCP to connect to a web server, how is the port selected? Does the web browser select which port it will use?


When using TCP to connect to a web server, how is the port selected? Does the web browser select which port it will use?

A web server usually listens on port 80. Apache web server is a popular web server, and nginx is another popular web server. Is it possible to have Apache web server and nginx both running on my server at the same time?

How many sockets (across all machines involved) are required for a TCP connection? How many are required for a UDP connection?


Solution

  • When the http client parses the uri http://www.my_site.net/, since no port is explicitly provided, then 80 is assumed by default to reach the server. On the other hand, if the uri looks like http://www.my_site.net:8080/, then the explicitly provided port number 8080 will be used to reach the server. Note that this is the destination port from the client point of view; the source port of a client is generally an arbitrary free port automaticaly assigned by the system.

    You cannot have several TCP servers listening to the same port (80 for example) on a single system. If you want both apache and nginx running in the same system, you will have to change the listening port for one of them.

    From the client point of view, one single socket is involved in a TCP connection; the client creates this socket, connects it to the server then sends/receives data through this same socket. From the server point of view two sockets are necessary for a TCP connection, and more generally N+1 sockets are necessary for N connections. The +1 socket is called the listen-socket; it is bound to the port (80 for exemple) on which the server should be reached. As soon as a client connects to this listen-socket, the server should accept this connection which makes a dialog-socket appear; this dialog-socket is used to send/receive data with the connected client.