MSDN Documentation

Windows Networking | Examples

UDP Client Example

This document provides a C++ example of a basic User Datagram Protocol (UDP) client application for Windows. UDP is a connectionless protocol, making it suitable for applications where speed is critical and some data loss is acceptable, such as streaming media or online gaming.

Overview

The following code demonstrates how to:

Prerequisites

Code Example

This example uses the Winsock 2 API. Ensure you include the necessary headers and link against the Winsock library.

// Ensure Winsock is initialized #include <winsock2.h> #include <ws2tcpip.h> #include <iostream> #include <string> #include <vector> // Link with Ws2_32.lib #pragma comment(lib, "Ws2_32.lib") const int DEFAULT_PORT = 27015; const int BUFFER_SIZE = 512; int main(int argc, char** argv) { // Initialize Winsock WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { std::cerr << "WSAStartup failed: " << iResult << std::endl; return 1; } // Create a SOCKET for sending data SOCKET ClientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (ClientSocket == INVALID_SOCKET) { std::cerr << "socket failed with error: " << WSAGetLastError() << std::endl; WSACleanup(); return 1; } // Set up the server address structure sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(DEFAULT_PORT); // Convert the IP address to a network format // For simplicity, using localhost. Replace with actual IP if needed. // You can also use inet_pton for IPv6 compatibility if (InetPton(AF_INET, L"127.0.0.1", &serverAddr.sin_addr) == 0) { std::cerr << "InetPton failed." << std::endl; closesocket(ClientSocket); WSACleanup(); return 1; } // Data to send std::string message = "Hello, UDP Server!"; char sendBuffer[BUFFER_SIZE]; strcpy_s(sendBuffer, BUFFER_SIZE, message.c_str()); // Send data std::cout << "Sending: " << message << " to " << "127.0.0.1:" << DEFAULT_PORT << std::endl; iResult = sendto(ClientSocket, sendBuffer, (int)strlen(sendBuffer), 0, (sockaddr*)&serverAddr, sizeof(serverAddr)); if (iResult == SOCKET_ERROR) { std::cerr << "sendto failed with error: " << WSAGetLastError() << std::endl; closesocket(ClientSocket); WSACleanup(); return 1; } std::cout << "Sent " << iResult << " bytes." << std::endl; // Optional: Receive response from server char recvBuffer[BUFFER_SIZE]; int bytesReceived; int serverAddrSize = sizeof(serverAddr); std::cout << "Waiting for response..." << std::endl; bytesReceived = recvfrom(ClientSocket, recvBuffer, BUFFER_SIZE, 0, (sockaddr*)&serverAddr, &serverAddrSize); if (bytesReceived > 0) { recvBuffer[bytesReceived] = '\0'; // Null-terminate the received data std::cout << "Received " << bytesReceived << " bytes from " << inet_ntoa(serverAddr.sin_addr) << ":" << ntohs(serverAddr.sin_port) << std::endl; std::cout << "Data: " << recvBuffer << std::endl; } else if (bytesReceived == 0) { std::cout << "Connection closed by server." << std::endl; } else { std::cerr << "recvfrom failed with error: " << WSAGetLastError() << std::endl; } // Cleanup closesocket(ClientSocket); WSACleanup(); return 0; }

Explanation of Key Components

Compiling and Running

  1. Save the code as a .cpp file (e.g., udp_client.cpp).
  2. Compile the code using a C++ compiler like Visual Studio. Ensure you link against Ws2_32.lib.
  3. You will need a corresponding UDP server application running on the specified IP address and port (e.g., 127.0.0.1 on port 27015) to receive the message and potentially send a response.

Further Considerations

Related Topics