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:
- Source Port (16 bits): Identifies the sender’s port number.
- Destination Port (16 bits): Identifies the recipient’s port number.
- Length (16 bits): Specifies the length of the UDP header and data in bytes.
- 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
import socket
import sys- Socket Module: Provides low-level networking functionality.
- sys Module: Provides access to some variables used or maintained by the interpreter.
Server Configuration
SERVER_IP = "127.0.0.1"
SERVER_PORT = 6789- Server IP and Port Configuration: Specifies the IP address and port on which the server will listen for incoming datagrams.
Socket Creation and Binding
socket_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket_server.bind((SERVER_IP, SERVER_PORT))- Socket Creation: Creates a socket for IPv4 (AF_INET) and UDP (SOCK_DGRAM) communication.
- Binding: Binds the socket to the specified IP address and port.
Server Initialization
print("[*] Server UDP Listening on %s:%d" % (SERVER_IP, SERVER_PORT))- Print Information: Prints that the UDP server is listening on a specific IP and port.
Data Reception and Response Loop
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))- Data Reception: Listens for incoming datagrams using
recvfrom. - Acknowledgment Response: Sends an acknowledgment message to the client using
sendto. - Prints Received Message: Prints the received message and the address of the sender.
Response Generation
try:
response = "Hi %s" % sys.platform
except Exception as e:
response = "%s" % sys.exc_info()[0]- Response Generation: Attempts to generate a response indicating the platform the server is running on. If an exception occurs, it captures the exception information.
Sending Response
print("Response", response)
socket_server.sendto(bytes(response, encoding='utf8'), address)- Response Printing: Prints the generated response.
- Sending Response: Sends the response back to the client using
sendto.
Infinite Loop (Server Continuity)
socket_server.close()- Infinite Loop: The server remains in an infinite loop to continuously receive and respond to incoming datagrams.
- Socket Closure: The
socket_serversocket is closed (Note: this line is unreachable due to the infinite loop, and it’s recommended to remove it or place it in an appropriate condition for graceful termination).
#!/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
import socket- Import Statement: Imports the
socketmodule for socket operations.
Server Configuration
SERVER_IP = "127.0.0.1"
SERVER_PORT = 6789- Server IP and Port Configuration: Specifies the IP address and port of the UDP server to which the client will send messages.
Socket Creation
address = (SERVER_IP, SERVER_PORT)
socket_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- Address Configuration: Creates a tuple
addresscontaining the server’s IP address and port. - Socket Creation: Creates a socket for IPv4 (AF_INET) and UDP (SOCK_DGRAM) communication.
Message Sending Loop
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)- Infinite Loop: Prompts the user to enter a message until the user enters “quit.”
- Message Sending: Sends the entered message to the server using
sendto. - Response Reception: Receives the response from the server using
recvfrom. - Response Printing: Prints the received response from the server.
Quit Condition
if message == "quit":
break- Quit Condition: Breaks out of the loop if the user enters “quit.”
Socket Closure
socket_client.close()- Socket Closure: Closes the client socket when the loop terminates.
#!/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.