MSDN Documentation

accept Function

The accept function retrieves the first connection pending on the socket specified by the listening socket.

SOCKET accept(
  _In_ SOCKET sockfd,
  _Out_opt_ struct sockaddr *addr,
  _Inout_opt_ int *addrlen
);

Parameters

Parameter Description
sockfd

A descriptor that identifies a socket that is in a listening state. The underlying provider must be able to accept connections on this socket.

addr

A pointer to a buffer that will receive the address of the connecting entity, as known to the communications activity associated with sockfd.

The detailed format of the addr parameter is determined by the address family established when the socket was created.

If addr is NULL, the information about the remote address is not returned.

addrlen

A pointer to an integer that specifies the size of the buffer pointed to by addr (in bytes).

When accept returns, this parameter is updated to indicate the actual size of the buffer occupied by the address of the remote entity.

If addrlen is NULL, the information about the remote address is not returned.

Return Value

If no error occurs, accept returns a descriptor for a newly created socket that is connected to the remote entity specified in addr. This returned socket is of the same type and address family as the original socket.

If an I/O error occurs, accept returns INVALID_SOCKET. To get extended error information, call WSAGetLastError.

Remarks

The accept function is used with connection-oriented protocols (such as the TCP protocol). It permits an arbitrary length of time to elapse between the calling of listen and the execution of accept.

The socket specified by sockfd is used to accept a connection. When a connection is pending on sockfd, accept picks up the connection and creates a new socket with the same properties of sockfd.

The new socket exists in a state where it is connected to the other end of the connection.

The original socket sockfd remains in a listening state, ready to accept other connections.

Note

For a non-blocking socket, accept will return SOCKET_ERROR if no connection is pending. You can use WSAGetLastError to check the error code. If the error code is WSAEWOULDBLOCK, no connection is currently available.

Warning

The addr and addrlen parameters are used to retrieve the address of the peer. Ensure that the buffer provided is large enough to hold the address information for the specified address family.

Example Usage


#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

#pragma comment(lib, "ws2_32.lib")

#define DEFAULT_PORT 27015

int main() {
    WSADATA wsaData;
    SOCKET listenSocket, clientSocket;
    struct sockaddr_in serverAddr, clientAddr;
    int clientAddrSize = sizeof(clientAddr);
    char buffer[1024] = {0};
    int bytesReceived;

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("WSAStartup failed.\n");
        return 1;
    }

    // Create a SOCKET for listening
    listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listenSocket == INVALID_SOCKET) {
        printf("socket failed: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    // Setup the server address structure
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(DEFAULT_PORT);

    // Bind the socket
    if (bind(listenSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        printf("bind failed: %d\n", WSAGetLastError());
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }

    // Listen for incoming connections
    if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
        printf("listen failed: %d\n", WSAGetLastError());
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }

    printf("Waiting for client connection...\n");

    // Accept a client connection
    clientSocket = accept(listenSocket, (struct sockaddr *)&clientAddr, &clientAddrSize);
    if (clientSocket == INVALID_SOCKET) {
        printf("accept failed: %d\n", WSAGetLastError());
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }

    printf("Client connected!\n");

    // Receive data from the client
    bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
    if (bytesReceived == SOCKET_ERROR) {
        printf("recv failed: %d\n", WSAGetLastError());
    } else if (bytesReceived > 0) {
        buffer[bytesReceived] = '\0'; // Null-terminate the received string
        printf("Received: %s\n", buffer);
    }

    // Clean up
    closesocket(clientSocket);
    closesocket(listenSocket);
    WSACleanup();

    return 0;
}
            

Requirements

Header: winsock2.h (include winsock2.h)

Library: Ws2_32.lib

DLL: Ws2_32.dll