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?
2
Answers
When the http client parses the uri
http://www.my_site.net/
, since no portis 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.
Web browser (or any other TCP client) may select the client port but it is usually done by OS. When TCP client just calls
socket()
and thenconnect()
then OS selects an ephemeral port. The exact algorithm depends on the OS internal and it is rather random port from application point of view.Yes it is possible but they cannot share the same port. For example you can configure nginx to listen on port 8080 and keep apache default configuration on port 80.
For TCP connection there is one socket at the client side and 2 sockets at the server side. The server side has one listening socket and one socket for each connected client.
For UDP there is one socket at the client side and one socket on the server side.