accept Function (Winsock)
Synopsis
SOCKET accept(
SOCKET s,
struct sockaddr *addr,
int *addrlen
);
Parameters
- s – A descriptor identifying the socket that will accept connections.
- addr – A pointer to a buffer that receives the address of the connecting entity. Can be
NULL
. - addrlen – On input, specifies the size of the buffer pointed to by
addr
. On output, receives the actual size of the address.
Return Value
If the function succeeds, the return value is a new socket descriptor for the accepted connection. If it fails, the return value is SOCKET_ERROR
. Call WSAGetLastError for extended error information.
Remarks
Typical usage
#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(5555);
bind(listenSock, (SOCKADDR*)&server, sizeof(server));
listen(listenSock, 5);
clientSock = accept(listenSock, (SOCKADDR*)&client, &clientLen);
if (clientSock == SOCKET_ERROR) {
printf("accept failed: %d\\n", WSAGetLastError());
return 1;
}
// Communicate with client using recv/send ...
closesocket(clientSock);
closesocket(listenSock);
WSACleanup();
return 0;
}
This snippet demonstrates a basic TCP server that creates a listening socket, binds it to a local port, and accepts an incoming connection.
Examples
Simple Echo Server
#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#define PORT 8080
#define BUF_SIZE 512
int main() {
WSADATA wsa;
SOCKET listener, client;
struct sockaddr_in server, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buf[BUF_SIZE];
int bytesRecv;
WSAStartup(MAKEWORD(2,2), &wsa);
listener = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
bind(listener, (SOCKADDR*)&server, sizeof(server));
listen(listener, 5);
printf("Server listening on port %d...\\n", PORT);
client = accept(listener, (SOCKADDR*)&clientAddr, &clientAddrLen);
if (client == SOCKET_ERROR) {
printf("accept error: %d\\n", WSAGetLastError());
return 1;
}
while ((bytesRecv = recv(client, buf, BUF_SIZE, 0)) > 0) {
send(client, buf, bytesRecv, 0);
}
closesocket(client);
closesocket(listener);
WSACleanup();
return 0;
}