How To Code a UDP Client-Server - Python

In this tutorial we'll learn how to code a UDP client and server in python using the socket module in python.
UDP or User Datagram Protocol is termed as a connectionless protocol.



UDP Server

Steps:

  • Create a socket
  • Bind the socket
  • Send/Recieve data
  • Close the socket

You can see in the steps we did not include 'listen for connection' and 'accept connection because UDP is a connectionless protocol, connection is needed not in order to send/receive data.
Let's start coding the server now.


  


import socket

# Our host, 0.0.0.0 means use any
# interface available on our device
host = "0.0.0.0"

# The port number to listen on
port = 8080

print("[$] Creating socket...")
# Create the server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("[$] Socket created successfully!")
print("[$] Binding socket...")
# bind the socket
try:
    server_socket.bind((host, port))
except socket.error as err:
    print(f"[-] Bind failed, {str(err)}")
    exit()
print("[$] Bind complete")

Note that this time we used socket.SOCK_DGRAM instead of socket.SOCK_STREAM because we're no longer gonna be using TCP so we used socket.SOCK_DGRAM which idicates the socket type to be Datagram(or UDP).
Next we'll receive some data from a client then echo back the same data to the client.


  


# receive data from client
buffer_size = 4096
data = server_socket.recvfrom(buffer_size)

message = data[0].decode()
address = data[1]
print(f"[$] Data received: {message} from {address[0]}:{address[1]}")
# send back the same message to the server
server_socket.sendto(message.upper().encode(), address)
server_socket.close()

Since this is a UDP socket, so we'll not be using the recv() function to recv data, we'll be using the recvfrom() function.
The recvfrom() function is used for receiving data from any client. It returns a 2 tuple, the first one is the actual data from the client, then the second one is also a tuple of the client address, which the first one is the client's IP address and the second is the client's port number.
we also used the sendto() function to send data to a specific address. So here we're echoing back the data to the client that sends us the data from the first place.

UDP Client

Steps:

  • Create a socket
  • Send/Recieve data
  • Close the socket

In UDP, we don;t actually have to connect to the server in order to send data that's why in the list of our steps there's no 'connect to the server'.
Client code:


  


import socket

# host to connect to
host = "127.0.0.1"
# port number to connect on
port = 8080

print("[$] Creating socket...")
# Create the client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("[$] Socket created successfully!")

data = "Hello Server"
client_socket.sendto(data.encode(), ((host, port)))

# receive data from the server
buffer_size = 4096
data = client_socket.recvfrom(buffer_size)

message = data[0].decode()
address = data[1]

print(f"[$] Data received: {message} from {address[0]}:{address[1]}")
client_socket.close()