Home > Back-end >  How does a client know which port to send data after accept()
How does a client know which port to send data after accept()

Time:12-18

Let's say we have a server that can accept multiple clients. First, it has to create a socket, then bind it with a port and an IP and finally listen to requests for connection from clients. After accept()ing a connection with a client, the server creates a new socket to communicate with the specific client. My question is whether or not the client is going to send its data to the same port it sent its initial request to, and if not how does it know where to send it?

CodePudding user response:

Generally There is always a default port allotted for each kind of communication.Operating System may kept it open or close ,it can be checked .

Let's say for FTP connection, There is a separate port allotted for handshake,It don't matter how many new FTP connection are being requested, all new connection will go to that same port , Once handshake is completed data exchange is done via another port, Even if we don't specify port. If Network manager has Port List entries earlier it will request to the same port.

Example for SSH if you request for

ssh -X <IP> 

Even if you don't mention port , Your system know which port to request for and at server side there is always some port open who will be listening to your request and based on data you send while handshake it will continue listening or block you.

Bonus is you can open your custom port at server side who will be listening to your request. TCP implementation by default declare which port will be used for what kind of communication.

CodePudding user response:

The client connects with a source IP and port to a server with a destination IP and port. After accept exactly the same IP and port on both sides are continued to be used for data exchange as for the establishment of the connection.

  • Related