Winsock Programming

This section provides comprehensive documentation for Windows Sockets (Winsock) programming. Winsock is a Microsoft Windows implementation of the Berkeley sockets API, providing a standard interface for Windows network applications.

Introduction to Winsock

Winsock allows developers to create network-aware applications by providing a set of functions, structures, and data types for network communication. It supports various network protocols, including TCP/IP, and enables both connection-oriented and connectionless communication.

Key Concepts

Getting Started with Winsock

To begin Winsock programming, you need to include the necessary header file and initialize the Winsock DLL. The process typically involves the following steps:

  1. Include <winsock2.h> and <ws2tcpip.h>.
  2. Create a WSADATA structure.
  3. Call WSAStartup() to initialize Winsock.
  4. Perform network operations using Winsock functions.
  5. Call WSACleanup() when your application is finished with Winsock.

Initialization Example


#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

// Link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsaData;
    int iResult;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    printf("Winsock initialized successfully.\n");

    // ... perform network operations ...

    // Cleanup Winsock
    WSACleanup();
    return 0;
}
            

Common Winsock Functions

Winsock provides a rich set of functions for managing network connections and transferring data. Here are some of the most frequently used ones:

socket()

Creates a socket that is an endpoint for communication.

SOCKET socket(int af, int type, int protocol);

bind()

Associates a local address with a socket.

int bind(SOCKET s, const struct sockaddr *name, int namelen);

connect()

Establishes a connection to a remote socket (for TCP).

int connect(SOCKET s, const struct sockaddr *name, int namelen);

listen()

Places a socket in a state where it listens for incoming connections (for TCP servers).

int listen(SOCKET s, int backlog);

accept()

Accepts a connection request on a listening socket (for TCP servers).

SOCKET accept(SOCKET s, struct sockaddr *addr, int *addrlen);

send()

Sends data on a connected socket.

int send(SOCKET s, const char *buf, int len, int flags);

recv()

Receives data from a connected socket.

int recv(SOCKET s, char *buf, int len, int flags);

Advanced Topics

For detailed information on each function and more complex examples, please refer to the individual API reference pages.