MSDN Documentation

Connectionless Sockets (UDP)

Connectionless sockets use the User Datagram Protocol (UDP) to send and receive packets without establishing a persistent connection. They are ideal for low‑latency, high‑throughput scenarios where occasional packet loss is acceptable.

Key Functions

int socket(int af, int type, int protocol);
int bind(int s, const struct sockaddr *addr, int namelen);
ssize_t sendto(int s, const void *buf, size_t len, int flags,
               const struct sockaddr *to, int tolen);
ssize_t recvfrom(int s, void *buf, size_t len, int flags,
                 struct sockaddr *from, int *fromlen);
int closesocket(SOCKET s);

Example: Simple UDP Echo Server (C++)

#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")

int main() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2), &wsaData);

    SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    sockaddr_in server{};
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(5150);
    bind(sock, (sockaddr*)&server, sizeof(server));

    char buffer[512];
    sockaddr_in client{};
    int clientLen = sizeof(client);

    while (true) {
        int received = recvfrom(sock, buffer, sizeof(buffer)-1, 0,
                                (sockaddr*)&client, &clientLen);
        if (received == SOCKET_ERROR) break;
        buffer[received] = '\0';
        sendto(sock, buffer, received, 0, (sockaddr*)&client, clientLen);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
}

Live Demo: UDP Packet Builder

Related Topics