Network Programming with UDP Protocol

Network Protocol Models

OSI Reference Model

  • Application Layer: Actual data being transmitted
  • Presentation Layer: Data encryption/decryption
  • Session Layer: Session establishment and connection management
  • Transport Layer: Data transmission methods (datagram, stream)
  • Network Layer: Data routing between networks (IP addressing)
  • Data Link Layer: Local network communication, switching, frame formatting, error checking
  • Physical Layer: Physical medium connection (e.g., 100Mb/8 Ethernet, 10GB fiber optic)

Wireless network frequencies include 2.4GHz and 5GHz bands.

TCP/IP Protocol Stack

  • Application Layer: Data content
  • Transport Layer: Transmission methods with port numbers (TCP/UDP)
  • Network Layer: Host-to-host communication (IP address, routing protocols like RIP, OSPF)
  • Interface Layer: Physical connection (network cards, drivers)

IP addresses may change, while MAC addresses remain unique and fixed.

Key Network Services

  • DNS: Domain Name System (e.g., www.example.com → 93.184.216.34)
  • DHCP: Dynamic Host Configuration Protocol for automatic IP address assignment

Application Layer Protocols

  • HTTP/HTTPS - Hypertext Transfer Protocol
  • FTP - File Transfer Protocol
  • TFTP - Trivial File Transfer Protocol
  • SMTP - Simple Mail Transfer Protocol
  • MQTT - Message Queuing Telemetry Transport
  • TELNET - Terminal Emulation Protocol

Transport Layer Protocols

UDP (User Datagram Protocol)

  • Simple implementation
  • Low resource overhead
  • Unreliable and insecure

TCP (Transmission Control Protocol)

  • Complex implementation
  • Higher resource overhead
  • Reliable and secure

Network Layer: IPv4 Addressing

An IP address uniquely identifies a host on a network and consists of network bits + host bits.

Subnet Masks

Subnet masks identify network and host portions of an IP address: - 1s represent network bits - 0s represent host bits

Network and Broadcast Addresses

  • Network Address: Network bits unchanged, host bits all 0s
  • Broadcast Address: Network bits unchanged, host bits all 1s

IP Address Classes

Class Range Default Subnet Mask Common Use
A 1.0.0.0 - 126.255.255.255 255.0.0.0 Large networks
B 128.0.0.0 - 191.255.255.255 255.255.0.0 Medium to large networks
C 192.0.0.0 - 223.255.255.255 255.255.255.0 Small to medium networks
D 224.0.0.0 - 239.255.255.255 - Multicasting
E 240.0.0.0 - 255.255.255.255 - Experimental

Private address ranges: - Class A: 10.0.0.0 - 10.255.255.255 - Class B: 172.16.0.0 - 172.31.255.255 - Class C: 192.168.0.0 - 192.168.255.255

Port Numbers

An IP address + port combination identifies a specific application on a host: - Port range: 1-65535 - Ports 1-1023 are typically system/reserved - Common ports: - HTTP: 80 - HTTPS: 443 - MySQL: 3306 - FTP: 21 - SSH: 22

Network Byte Order

Network devices operate in big-endian mode by default. IP addresses and port numbers require byte order conversion (host to network).

UDP Programming

Socket Programming Overview

Sockets are essentially file descriptors used for network communication.

Client/Server Model

  • Client (Sender): socket → sendto → close
  • Server (Receiver): socket → bind → recvfrom → close

Socket API Functions

Creating a Socket

int socket(int domain, int type, int protocol);

Creates a communication file descriptor.

  • domain: Protocol family (AF_INET for IPv4)
  • type: Socket type (SOCK_STREAM for TCP, SOCK_DGRAM for UDP)
  • protocol: Protocol (typically 0)
  • Return: File descriptor on success, -1 on failure

Sending Data

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
                const struct sockaddr *dest_addr, socklen_t addrlen);

Sends data to a specified address.

  • sockfd: Socket file descriptor
  • buf: Buffer containing data to send
  • len: Length of data to send
  • dest_addr: Destination address structure
  • addrlen: Length of address structure
  • Return: Number of bytes sent on success, -1 on failure

Receiving Data

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                  struct sockaddr *src_addr, socklen_t *addrlen);

Receives data from a socket.

  • sockfd: Socket file descriptor
  • buf: Buffer to store received data
  • len: Maximum length of data to receive
  • src_addr: Source address structure
  • addrlen: Pointer to length of address structure
  • Return: Number of bytes received on success, -1 on failure

Binding a Socket

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

Binds an IP address and port to a socket.

  • sockfd: Socket file descriptor
  • addr: Address structure to bind
  • addrlen: Length of address structure
  • Return: 0 on success, -1 on failure

Address Conversion Functions

  • inet_addr: Converts string IP to network address format
  • htons: Converts host short to network short (byte order)
  • ntohs: Converts network short to host short (byte order)
  • inet_ntoa: Converts network address to string IP

UDP Implementation Example

Common Header (common.h)

#ifndef _COMMON_H
#define _COMMON_H
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define SERVER_IP "192.168.1.100"
#define SERVER_PORT 8000
#define BUFFER_SIZE 1024
#endif

UDP Sender (udp_sender.c)

#include "common.h"

int main() {
    int sockfd;
    char buffer[BUFFER_SIZE];
    struct sockaddr_in server_addr;
    ssize_t bytes_sent;
    
    // Create UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }
    
    // Set up server address
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    
    // Convert IP address from string to network format
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("Invalid address");
        exit(EXIT_FAILURE);
    }
    
    printf("Enter message to send: ");
    fgets(buffer, BUFFER_SIZE, stdin);
    
    // Send message to server
    bytes_sent = sendto(sockfd, buffer, strlen(buffer), 0,
                       (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (bytes_sent < 0) {
        perror("Send failed");
        exit(EXIT_FAILURE);
    }
    
    printf("Message sent: %s", buffer);
    
    // Close socket
    close(sockfd);
    return 0;
}

UDP Receiver (udp_receiver.c)

#include "common.h"

int main() {
    int sockfd, ret;
    struct sockaddr_in server_addr, client_addr;
    socklen_t addr_len = sizeof(client_addr);
    char buffer[BUFFER_SIZE];
    ssize_t bytes_received;
    
    // Create UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }
    
    // Set up server address
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(SERVER_PORT);
    
    // Bind socket to address
    ret = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0) {
        perror("Bind failed");
        exit(EXIT_FAILURE);
    }
    
    printf("UDP Server waiting for messages...\n");
    
    // Receive messages
    while (1) {
        bytes_received = recvfrom(sockfd, buffer, BUFFER_SIZE, 0,
                                 (struct sockaddr *)&client_addr, &addr_len);
        if (bytes_received < 0) {
            perror("Receive failed");
            exit(EXIT_FAILURE);
        }
        
        // Null-terminate the received data
        buffer[bytes_received] = '\0';
        
        printf("Received from %s:%d - %s",
               inet_ntoa(client_addr.sin_addr),
               ntohs(client_addr.sin_port),
               buffer);
    }
    
    // This line won't be reached due to the infinite loop
    close(sockfd);
    return 0;
}

Build Configuration (Makefile)

CC = gcc
CFLAGS = -Wall -Wextra
TARGETS = udp_sender udp_receiver

all: $(TARGETS)

udp_sender: udp_sender.c common.h
	$(CC) $(CFLAGS) -o $@ $<

udp_receiver: udp_receiver.c common.h
	$(CC) $(CFLAGS) -o $@ $<

clean:
	rm -f $(TARGETS)

.PHONY: all clean

Tags: Network Programming udp Socket Programming network protocols client-server

Posted on Sat, 18 Jul 2026 17:05:33 +0000 by jonny 5ive