Accepts a connection on a socket
The accept function retrieves the first connection on the queue of pending connections, creates a new socket with the same properties of the original socket, and allocates a new file descriptor for that socket. It then associates the returned socket with the address of the client.
SOCKET accept(
SOCKET s,
struct sockaddr * addr,
LPINT addrlen
);
INVALID_SOCKET is returned.
WSAGetLastError.
The accept function permits a pending connection on the socket s to be created. The socket returned by accept is a completely new socket, and it is used to communicate with the client. The original socket s continues to be in a listening state, ready to accept other connection requests.
The addr and addrlen parameters are value-result parameters. They are used to obtain the address of the client for the connection. If addr is not NULL and the underlying network supports it, the kernel fills the sockaddr structure with the peer address. The value pointed to by addrlen, on input, is the size of this buffer. On output, the value is the actual length of the address returned.
If addr or addrlen are NULL, the information concerning the remote client's address is not returned.
If the socket descriptor s is a non-blocking socket, and there are no pending connections to accept, accept will return SOCKET_ERROR and WSAGetLastError will return WSAEWOULDBLOCK.
This function blocks the calling thread until a connection is established. You can use the select function to determine when a socket is ready to accept a connection.
Note that for TCP/IP, the accept function works in conjunction with the socket, bind, and listen functions.
SOCKET listen_socket, accept_socket;
struct sockaddr_in client_addr;
int client_addr_size = sizeof(client_addr);
// ... (socket creation, bind, listen done on listen_socket) ...
accept_socket = accept(listen_socket, (struct sockaddr*)&client_addr, &client_addr_size);
if (accept_socket == INVALID_SOCKET) {
// Handle error
} else {
// Connection accepted, use accept_socket for communication
}