Winsock API Reference
Overview
The Windows Sockets (Winsock) API provides a standardized interface for network communication using the TCP/IP protocol suite. It is based on the Berkeley sockets API and extends it with Windows‑specific features.
Header Files
Include the following headers in your source files:
#include <winsock2.h>#include <ws2tcpip.h>#include <mswsock.h>
Link against Ws2_32.lib.
Functions
WSAStartup
Prototype: int WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);
Initializes the Winsock DLL. Must be called before any other Winsock function.
socket
Prototype: SOCKET socket(int af, int type, int protocol);
Creates a new socket descriptor.
bind
Prototype: int bind(SOCKET s, const struct sockaddr *name, int namelen);
Binds a local address to a socket.
listen
Prototype: int listen(SOCKET s, int backlog);
Marks a socket as a listening socket for incoming connections.
accept
Prototype: SOCKET accept(SOCKET s, struct sockaddr *addr, int *addrlen);
Accepts an incoming connection request.
connect
Prototype: int connect(SOCKET s, const struct sockaddr *name, int namelen);
Initiates a connection on a socket.
send
Prototype: int send(SOCKET s, const char *buf, int len, int flags);
Sends data on a connected socket.
recv
Prototype: int recv(SOCKET s, char *buf, int len, int flags);
Receives data from a connected socket.
closesocket
Prototype: int closesocket(SOCKET s);
Closes an existing socket.
WSACleanup
Prototype: int WSACleanup(void);
Terminates use of the Winsock DLL. Call after all sockets are closed.
Structures
Commonly used structures include:
sockaddr_in– IPv4 address structure.sockaddr_in6– IPv6 address structure.addrinfo– Used withgetaddrinfo.fd_set– Used withselect.
Constants
| Macro | Description |
|---|---|
AF_INET | IPv4 address family |
AF_INET6 | IPv6 address family |
SOCK_STREAM | TCP socket type |
SOCK_DGRAM | UDP socket type |
IPPROTO_TCP | TCP protocol |
IPPROTO_UDP | UDP protocol |
INVALID_SOCKET | Invalid socket descriptor |
SOCKET_ERROR | Function error return |
Sample Code
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
int main() {
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
const char *msg = "Hello, Winsock!";
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
printf("WSAStartup failed. Error: %d\n", WSAGetLastError());
return 1;
}
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
printf("Socket creation failed. Error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
server.sin_family = AF_INET;
server.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
if (connect(s, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {
printf("Connect failed. Error: %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
send(s, msg, (int)strlen(msg), 0);
closesocket(s);
WSACleanup();
return 0;
}