socket programming - why web server still using listen port 80 to communicate with client even after they accepted the connection?

前端 未结 5 660
渐次进展
渐次进展 2021-01-21 05:13

Usually a web server is listening to any incoming connection through port 80. So, my question is that shouldn\'t it be that in general concept of socket programming is that port

5条回答
  •  鱼传尺愫
    2021-01-21 05:48

    A particular socket is uniquely identified by a 5-tuple (i.e. a list of 5 particular properties.) Those properties are:

    1. Source IP Address
    2. Destination IP Address
    3. Source Port Number
    4. Destination Port Number
    5. Transport Protocol (usually TCP or UDP)

    These parameters must be unique for sockets that are open at the same time. Where you're probably getting confused here is what happens on the client side vs. what happens on the server side in TCP. Regardless of the application protocol in question (HTTP, FTP, SMTP, whatever,) TCP behaves the same way.

    When you open a socket on the client side, it will select a random high-number port for the new outgoing connection. This is required, otherwise you would be unable to open two separate sockets on the same computer to the same server. Since it's entirely reasonable to want to do that (and it's very common in the case of web servers, such as having stackoverflow.com open in two separate tabs) and the 5-tuple for each socket must be unique, a random high-number port is used as the source port. However, each of those sockets will connect to port 80 at stackoverflow.com's webserver.

    On the server side of things, stackoverflow.com can already distinguish between those two different sockets from your client, again, because they already have different client-side port numbers. When it sees an incoming request packet from your browser, it knows which of the sockets it has open with you to respond to because of the different source port number. Similarly, when it wants to send a response packet to you, it can send it to the correct endpoint on your side by setting the destination port number to the client-side port number it got the request from.

    The bottom line is that it's unnecessary for each client connection to have a separate port number on the server's side because the server can already uniquely identify each client connection by its client IP address and client-side port number. This is the way TCP (and UDP) sockets work regardless of application-layer protocol.

提交回复
热议问题