Skip to content

Instantly share code, notes, and snippets.

@eburlingame
Created November 19, 2018 18:15
Show Gist options
  • Save eburlingame/dbf68faf7427cc10273e3c67ffbd448e to your computer and use it in GitHub Desktop.
Save eburlingame/dbf68faf7427cc10273e3c67ffbd448e to your computer and use it in GitHub Desktop.
Simple UDP client in C using winsock2
// UDPListener.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <windows.h> // Needed for all Winsock stuff
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define PORT_NUM 5001 // Port number used
#define IP_ADDR "127.0.0.1" // IP address of server1 (*** HARDWIRED ***)
#define NET_BUFF_SIZE 400
void NET_recv(int client, sockaddr_in server_addr, char *buffer)
{
char data_out[NET_BUFF_SIZE];
int addr_len = sizeof(server_addr);
int retcode = recvfrom(client, data_out, NET_BUFF_SIZE, 0, (struct sockaddr *)&server_addr, &addr_len);
if (retcode < 0)
{
int err = WSAGetLastError();
printf("recvfrom() failed with error code : %d\n", err);
return;
}
data_out[ retcode ] = 0;
memcpy(buffer, data_out, retcode + 1);
}
int setup_socket(int *client_s, sockaddr_in *server_addr, int port_num)
{
WORD wVersionRequested = MAKEWORD(1, 1); // Stuff for WSA functions
WSADATA wsaData; // Stuff for WSA functions
int opt = 1;
WSAStartup(wVersionRequested, &wsaData);
server_addr->sin_family = AF_INET; // Address family to use
server_addr->sin_port = htons(port_num); // Port num to use
server_addr->sin_addr.S_un.S_addr = inet_addr(IP_ADDR);
*client_s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (client_s < 0)
{
printf("*** ERROR - socket() failed \n");
}
//UDP Broadcast permissions
if (setsockopt(*client_s, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt)) == SOCKET_ERROR)
{
printf("\nERROR in broadcasting ERROR CODE : %d \n", WSAGetLastError());
closesocket(*client_s);
WSACleanup();
return 1;
}
//UDP SOCKET Binding
if (bind(*client_s, (sockaddr *)server_addr, sizeof(sockaddr_in)) == SOCKET_ERROR)
{
int err = WSAGetLastError();
printf("\nUDP socket binding failed ERROR CODE : %d\n", err);
closesocket(*client_s);
WSACleanup();
return 1;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int client_s;
sockaddr_in server_addr;
char buffer[ NET_BUFF_SIZE ];
printf("Setting up...\n");
setup_socket(&client_s, &server_addr, PORT_NUM);
while (true) {
NET_recv(client_s, server_addr, buffer);
printf("%s\n", buffer);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment