Skip to content

xyurt/udp-wrapper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

UDP Wrapper (C)

A simple C89 style sockets wrapper for exclusively udp operations with a simple API.

Server & Client Example

Here is a minimal server and client example in a simple .c file

#include <stdio.h>

#include "udp.h"

#pragma comment(lib, "ws2_32.lib")

#define CLIENT_MODE (0)

udp_address_t server_address;
unsigned long server_port = 3169;

void server() {
	udp_socket sockfd = udp_socket_create();
	if (IS_SOCKET_INVALID(sockfd))
		return;

	int err = udp_socket_bind(sockfd, &server_address);
	if (err < 0) {
		printf("Bind operation failed, errno: (%d)\n", err);
		return;
	}

	printf("Server listening...\n");

	char recvbuf[4096];
	int recvlen;
	udp_address_t recvaddr;

	for (;;) {
		recvlen = udp_socket_recv(sockfd, recvbuf, sizeof(recvbuf), &recvaddr);
		if (recvlen < 0) {
			printf("recvlen < 0, errno: (%d)\n", recvlen);
			return;
		}

		printf("Received (%d) bytes of data: (%.*s)\n", recvlen, recvlen, recvbuf);
		break;
	}
}
void client() {
	udp_socket sockfd = udp_socket_create();
	if (IS_SOCKET_INVALID(sockfd))
		return;

	int sendlen = udp_socket_send(sockfd, "Hello, World!", 14, &server_address);
	if (sendlen < 0) {
		printf("Recv operation failed, errno: (%d)\n", sendlen);
		return;
	}

	for (int i = 0; i < 10; i++) {
		printf("Sent (%d) bytes of data to the server.\n", sendlen);
		Sleep(1000);
	}
}

int main(void) {

	udp_init();

	udp_address_set(&server_address, UDP_LOCALHOST6, server_port);

	if (CLIENT_MODE) {
		client();
	}
	else {
		server();
	}

	printf("Cleaning up...\n");

	udp_cleanup();

	return 0;
}

Includes

udp.h includes

—WIN32

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

—UNIX

#include <sys/socket.h>

Structures

udp_address structure:

typedef struct udp_address {
	struct sockaddr_storage data;
	size_t len;
} udp_address_t;

The fields of this structure must not be directly set, instead use udp_address_set().

Types

typedef UDP_SOCKET_TYPE udp_socket;

udp_socket is SOCKET on WIN32, int on UNIX.

Definitions

UDP_ANY: = "0.0.0.0"
UDP_ANY6: = "::"
UDP_LOCALHOST: = "127.0.0.1"
UDP_LOCALHOST6: = "::1"
IS_SOCKET_INVALID(sockfd): Returns (1) if the socket is invalid

Errno mapping

On WIN32, WSAGetLastError() return values are mapped as:

WSAEINVAL -> EINVAL  
WSAEADDRINUSE -> EADDRINUSE  
WSAEADDRNOTAVAIL -> EADDRNOTAVAIL  
WSAEFAULT -> EFAULT  
WSAENOTSOCK -> ENOTSOCK  
WSAEINTR -> EINTR  
WSAEWOULDBLOCK -> EAGAIN  
WSAECONNRESET -> ECONNRESET  
WSAENOBUFS -> ENOBUFS  
default -> EIO

The static function wsa_to_errno() handles the mappings in win32.c.

LICENSE

MIT

Releases

No releases published

Packages

 
 
 

Contributors

Languages