I have a question about the accept()
function in C.
When a server receive a connection, the accept()
function creates a new socket to communicate with the client, and then let the "old socket" listening 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 don't know about this "new socket") ?
The .accept() method blocks execution and waits for an incoming connection. When a client connects, it returns a new socket object representing the connection and a tuple holding the address of the client. The tuple will contain (host, port) for IPv4 connections or (host, port, flowinfo, scopeid) for IPv6.
The accept() method of ServerSocket class is used to accept the incoming request to the socket. To complete the request, the security manager checks the host address, port number, and localport.
The accept() system call with the connection-based socket types(SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on queue of pending connections for the listening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket.
RETURN VALUE Upon successful completion, accept() shall return the non-negative file descriptor of the accepted socket. Otherwise, -1 shall be returned and errno set to indicate the error.
On the server side, the listening socket is associated with only a local IP and port and is in the LISTEN state.
In contrast, accepted sockets on the server (as well as connected sockets on the client) are identified by a local IP and port as well as a remote IP and port and is in the ESTABLISHED state.
On the client side, it doesn't matter that the server uses a listening socket separate from the connected socket. By the time the client returns from connect
, the server has returned from accept
and the socket descriptors returned from each can communicate with each other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With