Connection Establishment
Establishing a TCP connection with Winsock involves a series of well‑defined steps. Below is a concise guide that covers both client‑side and server‑side procedures.
Client‑Side Flow
- Initialize Winsock with
WSAStartup
. - Create a socket using
socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
. - Resolve the server address (e.g.,
getaddrinfo
). - Connect with
connect()
to the server’ssockaddr_in
. - Check the return value – on success it returns 0; on failure use
WSAGetLastError
.
Client Example (C++)
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = nullptr, hints;
WSAStartup(MAKEWORD(2,2), &wsaData);
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo("example.com", "80", &hints, &result);
ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
connect(ConnectSocket, result->ai_addr, (int)result->ai_addrlen);
// Use ConnectSocket for send/recv...
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
Server‑Side Flow
- Initialize Winsock with
WSAStartup
. - Create a listening socket (
socket
). - Bind the socket to a local address/port via
bind()
. - Listen for incoming connections with
listen()
. - Accept a connection using
accept()
, which returns a new socket for the client. - Optionally, set socket options (e.g.,
setsockopt
for timeouts).
Server Example (C++)
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET, ClientSocket = INVALID_SOCKET;
struct addrinfo hints, *result = nullptr;
WSAStartup(MAKEWORD(2,2), &wsaData);
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "27015", &hints, &result);
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
listen(ListenSocket, SOMAXCONN);
ClientSocket = accept(ListenSocket, NULL, NULL);
// Use ClientSocket for send/recv...
closesocket(ClientSocket);
closesocket(ListenSocket);
WSACleanup();
return 0;
}
Common Pitfalls
- Not calling
WSAStartup
before any other Winsock function. - Ignoring the return value of
connect
oraccept
– always check errors. - For IPv6 compatibility, use
AF_UNSPEC
in hints and handle both address families. - Failing to close sockets (use
closesocket
) can exhaust system resources.