MSDN

Windows API Reference

Accept function

Synopsis

#include <winsock2.h>
int accept(
    SOCKET s,
    struct sockaddr *addr,
    int *addrlen
);

Description

The accept function extracts the first pending connection request on the listening socket s, creates a new socket for the connection, and returns the descriptor of that new socket. The original socket s remains open and can be used to accept further connections.

Parameters

ParameterDescription
sDescriptor of a socket that is bound to a local address and is listening for connections.
addrPointer to a sockaddr structure that receives the address of the connecting entity. Can be NULL if not needed.
addrlenPointer to an integer that specifies the size of the addr buffer. On return, it contains the actual size of the address.

Return Value

On success, returns a new socket descriptor for the accepted connection. On error, returns INVALID_SOCKET and WSAGetLastError provides the error code.

Remarks

Example

#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsa;
    SOCKET listenSock, clientSock;
    struct sockaddr_in server, client;
    int clientLen = sizeof(client);

    WSAStartup(MAKEWORD(2,2), &wsa);
    listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(8080);
    bind(listenSock, (struct sockaddr*)&server, sizeof(server));
    listen(listenSock, SOMAXCONN);

    clientSock = accept(listenSock, (struct sockaddr*)&client, &clientLen);
    if (clientSock != INVALID_SOCKET) {
        const char *msg = "Hello from server!\n";
        send(clientSock, msg, (int)strlen(msg), 0);
        closesocket(clientSock);
    }
    closesocket(listenSock);
    WSACleanup();
    return 0;
}

See Also