Skip to content

Windows Platform Examples

Niki Mardari edited this page Apr 2, 2026 · 7 revisions

Supported Systems

  • Windows 10 or newer
  • Other Windows systems with Winsock 2 or support like Windows 98 with ws2_32.dll

Why Windows is Different

Windows socket programming uses Winsock rather than the standard POSIX socket API.

Windows sockets require:

  • Explicit initialization with WSAStartup()
  • Explicit cleanup with WSACleanup()
  • Windows-specific socket headers such as winsock2.h and ws2tcpip.h
  • closesocket() instead of close()
  • WSAGetLastError() instead of errno
  • Linking against the Winsock library (Ws2_32)

Because of these differences, POSIX socket code cannot be reused directly on Windows without modification.

Supported Systems

  • Windows
  • Windows systems with MinGW/MSYS2 or another GCC-based toolchain
  • Other Windows C development environments supporting Winsock

Windows TCP Client Example (client.c)

Purpose: Demonstrates how to:

  • Initialize Winsock
  • Create a TCP socket
  • Connect to a remote server
  • Send data over the connection
  • Receive and print the response
  • Close the socket and clean up Winsock

High-level Flow:

  • Start Winsock with WSAStartup()
  • Convert the IPv4 string into a network address with inet_addr()
  • Create a TCP socket
  • Connect to the remote server
  • Send a request/message
  • Receive the response
  • Close the socket with closesocket()
  • Clean up Winsock with WSACleanup()

Functions:

  • WSAStartup()
  • WSACleanup()
  • socket()
  • connect()
  • send()
  • recv()
  • closesocket()
  • inet_addr()
  • WSAGetLastError()

Windows TCP Server Example (server.c)

Purpose: Demonstrates how to:

  • Initialize Winsock
  • Create a TCP listening socket
  • Bind the socket to a local port
  • Listen for incoming client connections
  • Accept a client connection
  • Send a simple response message
  • Close sockets and clean up Winsock

High-level Flow:

  • Start Winsock with WSAStartup()
  • Create a TCP socket
  • Bind the socket to a local port
  • Place the socket into listening mode
  • Accept one incoming client connection
  • Send a simple message to the client
  • Close the client socket
  • Close the listening socket
  • Clean up Winsock with WSACleanup()

Functions:

  • WSAStartup()
  • WSACleanup()
  • socket()
  • bind()
  • listen()
  • accept()
  • send()
  • closesocket()
  • sockaddr_in
  • htons()
  • htonl()
  • INADDR_ANY
  • WSAGetLastError()

Notes

  • The client and server must use the same port number in order to communicate.
  • For local testing, the client can connect to 127.0.0.1.
  • The example server is a simple TCP message server, not a full HTTP server.
  • When building with GCC/MinGW, the program must be linked with -lws2_32.

Clone this wiki locally