Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active Sep 27, 2022
Embed
What would you like to do?
client server UDP C++ example
CLIENT SIDE:
#include <iostream>
#include <winsock2.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
#define SERVER "127.0.0.1" // or "localhost" - ip address of UDP server
#define BUFLEN 512 // max length of answer
#define PORT 8888 // the port on which to listen for incoming data
int main()
{
system("title UDP Client");
// initialise winsock
WSADATA ws;
printf("Initialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &ws) != 0)
{
printf("Failed. Error Code: %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
// create socket
sockaddr_in server;
int client_socket;
if ((client_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) // <<< UDP socket
{
printf("socket() failed with error code: %d", WSAGetLastError());
return 2;
}
// setup address structure
memset((char*)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.S_un.S_addr = inet_addr(SERVER);
// start communication
while (true)
{
char message[BUFLEN];
printf("Enter message: ");
cin.getline(message, BUFLEN);
// send the message
if (sendto(client_socket, message, strlen(message), 0, (sockaddr*)&server, sizeof(sockaddr_in)) == SOCKET_ERROR)
{
printf("sendto() failed with error code: %d", WSAGetLastError());
return 3;
}
// receive a reply and print it
// clear the answer by filling null, it might have previously received data
char answer[BUFLEN] = {};
// try to receive some data, this is a blocking call
int slen = sizeof(sockaddr_in);
int answer_length;
if (answer_length = recvfrom(client_socket, answer, BUFLEN, 0, (sockaddr*)&server, &slen) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code: %d", WSAGetLastError());
exit(0);
}
cout << answer << "\n";
}
closesocket(client_socket);
WSACleanup();
}
==========================================================================================================================
SERVER SIDE:
#include <iostream>
#include <winsock2.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib") // Winsock Library
#pragma warning(disable:4996)
#define BUFLEN 512
#define PORT 8888
int main()
{
system("title UDP Server");
sockaddr_in server, client;
// initialise winsock
WSADATA wsa;
printf("Initialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code: %d", WSAGetLastError());
exit(0);
}
printf("Initialised.\n");
// create a socket
SOCKET server_socket;
if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket: %d", WSAGetLastError());
}
printf("Socket created.\n");
// prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
// bind
if (bind(server_socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code: %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done.");
while (true)
{
printf("Waiting for data...");
fflush(stdout);
char message[BUFLEN] = {};
// try to receive some data, this is a blocking call
int message_len;
int slen = sizeof(sockaddr_in);
if (message_len = recvfrom(server_socket, message, BUFLEN, 0, (sockaddr*)&client, &slen) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code: %d", WSAGetLastError());
exit(0);
}
// print details of the client/peer and the data received
printf("Received packet from %s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
printf("Data: %s\n", message);
cin.getline(message, BUFLEN);
// reply the client with 2the same data
if (sendto(server_socket, message, strlen(message), 0, (sockaddr*)&client, sizeof(sockaddr_in)) == SOCKET_ERROR)
{
printf("sendto() failed with error code: %d", WSAGetLastError());
return 3;
}
}
closesocket(server_socket);
WSACleanup();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment