How does the accept () function work?

I have a question about a function accept()in C.

When the server receives a connection, the function accept()creates a new socket to communicate with the client, and then allows the "old socket" to listen for new connections.

Then I understand that the server can communicate with the client through the "new socket", but how can the client communicate with the "new socket" (because the client does not know about this "new socket")?

+4
source share
4 answers

On the server side, the listening socket is only associated with the local IP address and port and is in the LISTEN state.

, ( ) IP- , IP- ESTABLISHED.

, . connect, accept, , , .

+6

IP ( TCP/IP) . : . TCP . , .

, 2 , 2 accept(), 2 .

netstat -an unix:

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN
tcp        0      0 170.44.26.7:22              161.231.133.178:11550       ESTABLISHED
tcp        0      0 170.44.26.7:22              161.231.133.178:33938       ESTABLISHED
tcp        0      0 170.44.26.7:22              161.231.133.178:13875       ESTABLISHED
tcp        0      0 170.44.26.7:22              161.231.133.178:34968       ESTABLISHED
tcp        0      0 170.44.26.7:22              161.231.133.178:44212       ESTABLISHED
tcp        0      0 170.44.26.7:22              161.231.133.178:34967       ESTABLISHED

( ) accept() .

+2

- API . , , API , .., - API .

+1

The explanation is that TCP (the endpoint in TCP / IP transmission) is uniquely identified by the IPaddress / port_number pair. When a client requests a connection, it uses its IP and port number, a unique pair. This operation associates SRCIP + SRCPORT with DSTIP + DSTPORT, and these 4 numbers (two IP addresses plus two ports) uniquely identify the connection. So the two sockets on the server really belong to two different connections / threads.

0
source

Source: https://habr.com/ru/post/1666036/


All Articles