networking - How does the socket API accept() function work? -


Socket API is D-FEC standard for TCP / IP and UDP / IP communication (i.e., networking code as we know is). However, one of its basic functions, accept () is a bit magical.

Borrow a semi-formal definition:

Accept () is used on the server side, an upcoming attempt to create a new TCP connection from this remote client Accept, and the socket address of this connection creates a new socket attached to the pair.

In other words, accept gives a new socket through which the server can communicate with the new connected client.

How does accept work? The old socket (where acceptance was called) remains open on the same port.

How is this implemented? There is a lot of confusion on this subject. Many people accept the claim that a new port opens and you communicate with the customer through it. But this is clearly not true, because no new port is opened. You can actually communicate with different customers through a single port, but how? When many threads call recv on the same port, how do the data know how to go?

I think that the name of the client's address is associated with some socket descriptor, and whenever the data comes through the recv , it converts it to the right socket Goes, but I'm not sure.

Your illusion is rooted in thinking that a socket server IP is recognized by the server port. In reality, the chairs are typically identified with information quartet:

client IP: client port and server IP: server port

So when the server IP and server port are stationary in all acceptable connections, the client side information is where it allows to keep track of where everything is going on.

To illustrate the examples:

Say that we have a server at 192.168.1.1:80 and two clients, 10.0.0.1 and 10.0.0.2.

10.0.0.1 opens a connection to the local port 1234 and connects to the server Now a socket of the server is identified as follows:

10.0.0.1:1234 - 192.168.1.1:80

Now 10.0.0.2 opens a connection to local port 5678 and connects to the server. Now the server has two sockets that have been identified as follows:

10.0.0.11234 - 192.168.1.1:80
10.0.0.2:5678 - 192.168.1.1:80


Comments