Implementing a simple UDP server and Client in Python

Implementing a simple UDP server and Client in Python

UDP (User Datagram Protocol) is one of the core protocols of the Internet protocol suite. It is a connectionless and lightweight transport protocol that operates on top of the Internet Protocol (IP). Unlike TCP, UDP does not provide reliability, ordering of data, or error recovery. It is commonly used for applications where low latency and reduced overhead are more critical than guaranteed delivery, such as real-time streaming and online gaming.

UDP Header

The UDP header is a simple structure that is part of a UDP datagram. It contains the following fields:

  1. Source Port (16 bits): Identifies the sender’s port number.
  2. Destination Port (16 bits): Identifies the recipient’s port number.
  3. Length (16 bits): Specifies the length of the UDP header and data in bytes.
  4. Checksum (16 bits): Used for error-checking the header and data (optional).

UDP Server and Client

UDP Server:

A UDP server is a program that listens for incoming UDP datagrams. Unlike TCP, UDP is connectionless, so there is no need to establish a connection before exchanging data.

This Python script is a simple UDP server that listens for incoming datagrams, responds to the sender with an acknowledgment, and then sends a platform-specific response to the client.

Import Statements

Python
import socket
import sys
  1. Socket Module: Provides low-level networking functionality.
  2. sys Module: Provides access to some variables used or maintained by the interpreter.

Server Configuration

Python
SERVER_IP = "127.0.0.1"
SERVER_PORT = 6789

Socket Creation and Binding

Python
socket_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket_server.bind((SERVER_IP, SERVER_PORT))
  1. Socket Creation: Creates a socket for IPv4 (AF_INET) and UDP (SOCK_DGRAM) communication.
  2. Binding: Binds the socket to the specified IP address and port.

Server Initialization

Python
print("[*] Server UDP Listening on %s:%d" % (SERVER_IP, SERVER_PORT))

Data Reception and Response Loop

Python
while True:
    data, address = socket_server.recvfrom(4096)
    socket_server.sendto("I am the server accepting connections...".encode(), address)
    data = data.strip()
    print("Message %s received from %s: " % (data, address))
  1. Data Reception: Listens for incoming datagrams using recvfrom.
  2. Acknowledgment Response: Sends an acknowledgment message to the client using sendto.
  3. Prints Received Message: Prints the received message and the address of the sender.

Response Generation

Python
    try:
        response = "Hi %s" % sys.platform
    except Exception as e:
        response = "%s" % sys.exc_info()[0]

Sending Response

Python
    print("Response", response)
    socket_server.sendto(bytes(response, encoding='utf8'), address)

Infinite Loop (Server Continuity)

Python
socket_server.close()
Python
#!/usr/bin/env python

import socket,sys

SERVER_IP = "127.0.0.1"
SERVER_PORT = 6789

socket_server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
socket_server.bind((SERVER_IP,SERVER_PORT))

print("[*] Server UDP Listening on %s:%d" % (SERVER_IP,SERVER_PORT))

while True:
	data,address = socket_server.recvfrom(4096)
	socket_server.sendto("I am the server accepting connections...".encode(),address)
	data = data.strip()
	print("Message %s received from %s: ",data, address)

	try:
		response = "Hi %s" % sys.platform
	except Exception as e:
		response = "%s" % sys.exc_info()[0]
	
	print("Response",response)
	
	socket_server.sendto(bytes(response,encoding='utf8'),address)
		
socket_server.close()

This script implements a UDP server that listens for datagrams, acknowledges the sender, and generates a response based on the server’s platform. The server continues to run indefinitely in a loop, continuously handling incoming datagrams.

UDP Client:

A UDP client is a program that sends UDP datagrams to a server. Similarly, since UDP is connectionless, there is no need to establish a connection before sending data.

Simple UDP client that allows a user to input messages, sends them to a UDP server, receives responses, and terminates upon entering “quit.”

Import Statement

Python
import socket

Server Configuration

Python
SERVER_IP = "127.0.0.1"
SERVER_PORT = 6789

Socket Creation

Python
address = (SERVER_IP, SERVER_PORT)
socket_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1. Address Configuration: Creates a tuple address containing the server’s IP address and port.
  2. Socket Creation: Creates a socket for IPv4 (AF_INET) and UDP (SOCK_DGRAM) communication.

Message Sending Loop

Python
while True:
    message = input("Enter your message > ")
    if message == "quit":
        break
    socket_client.sendto(bytes(message, encoding='utf8'), address)
    response_server, addr = socket_client.recvfrom(4096)
    print("Response from the server => %s" % response_server)
  1. Infinite Loop: Prompts the user to enter a message until the user enters “quit.”
  2. Message Sending: Sends the entered message to the server using sendto.
  3. Response Reception: Receives the response from the server using recvfrom.
  4. Response Printing: Prints the received response from the server.

Quit Condition

Python
    if message == "quit":
        break

Socket Closure

Python
socket_client.close()
Python
#!/usr/bin/env python

import socket

SERVER_IP = "127.0.0.1"
SERVER_PORT = 6789

address = (SERVER_IP ,SERVER_PORT)

socket_client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

while True:
	message = input("Enter your message > ")
	if message=="quit":
		break
	socket_client.sendto(bytes(message,encoding='utf8'),address)
	response_server,addr = socket_client.recvfrom(4096)
	print("Response from the server => %s" % response_server)
		
socket_client.close()

This script is a UDP client that interacts with a user, sending their input messages to a UDP server and displaying the responses. The client runs in an infinite loop until the user enters “quit.” It uses a UDP socket for communication with the server and closes the socket upon termination.

    Exit mobile version