- User Datagram Client and Server¶
- Echo Server¶
- Echo Client¶
- Client and Server Together¶
- UDP — Client And Server Example Programs In Python
- Properties of UDP:
- Example: UDP Server using Python
- Output:
- Example: UDP Client using Python
- Output:
- Send and receive UDP packets via Python
- Expectations:
- General Set Up Diagram:
- Assumptions or Limitations:
- Python files:
- Send/Receive UDP packet:
- How to run server.py in 192.168.1.102?
- How to run client.py in 192.168.1.6?
- Send or receive some text:
- Check UDP packet in Wireshark:
- Code explanation:
- Client code explanation:
- Server code explanation:
- Conclusion:
- References:
- About the author
- Bamdeb Ghosh
- RELATED LINUX HINT POSTS
User Datagram Client and Server¶
The user datagram protocol (UDP) works differently from TCP/IP. Where TCP is a stream oriented protocol, ensuring that all of the data is transmitted in the right order, UDP is a message oriented protocol. UDP does not require a long-lived connection, so setting up a UDP socket is a little simpler. On the other hand, UDP messages must fit within a single datagram (for IPv4, that means they can only hold 65,507 bytes because the 65,535 byte packet also includes header information) and delivery is not guaranteed as it is with TCP.
Echo Server¶
Since there is no connection, per se, the server does not need to listen for and accept connections. It only needs to use bind() to associate its socket with a port, and then wait for individual messages.
import socket import sys # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the socket to the port server_address = ('localhost', 10000) print('starting up on <> port <>'.format(*server_address)) sock.bind(server_address) while True: print('\nwaiting to receive message') data, address = sock.recvfrom(4096) print('received <> bytes from <>'.format( len(data), address)) print(data) if data: sent = sock.sendto(data, address) print('sent <> bytes back to <>'.format( sent, address))
Messages are read from the socket using recvfrom() , which returns the data as well as the address of the client from which it was sent.
Echo Client¶
The UDP echo client is similar the server, but does not use bind() to attach its socket to an address. It uses sendto() to deliver its message directly to the server, and recvfrom() to receive the response.
import socket import sys # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = ('localhost', 10000) message = b'This is the message. It will be repeated.' try: # Send data print('sending '.format(message)) sent = sock.sendto(message, server_address) # Receive response print('waiting to receive') data, server = sock.recvfrom(4096) print('received '.format(data)) finally: print('closing socket') sock.close()
Client and Server Together¶
Running the server produces:
$ python3 socket_echo_server_dgram.py starting up on localhost port 10000 waiting to receive message received 42 bytes from ('127.0.0.1', 57870) b'This is the message. It will be repeated.' sent 42 bytes back to ('127.0.0.1', 57870) waiting to receive message
$ python3 socket_echo_client_dgram.py sending b'This is the message. It will be repeated.' waiting to receive received b'This is the message. It will be repeated.' closing socket
UDP — Client And Server Example Programs In Python
UDP is the abbreviation of User Datagram Protocol. UDP makes use of Internet Protocol of the TCP/IP suit. In communications using UDP, a client program sends a message packet to a destination server wherein the destination server also runs on UDP.
Properties of UDP:
- The UDP does not provide guaranteed delivery of message packets. If for some issue in a network if a packet is lost it could be lost forever.
- Since there is no guarantee of assured delivery of messages, UDP is considered an unreliable protocol.
- The underlying mechanisms that implement UDP involve no connection-based communication. There is no streaming of data between a UDP server or and an UDP Client.
- An UDP client can send «n» number of distinct packets to an UDP server and it could also receive «n» number of distinct packets as replies from the UDP server.
- Since UDP is connectionless protocol the overhead involved in UDP is less compared to a connection based protocol like TCP.
Example: UDP Server using Python
msgFromServer = «Hello UDP Client»
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
print(«UDP server up and listening»)
# Listen for incoming datagrams
clientMsg = «Message from Client:<>«.format(message)
clientIP = «Client IP Address:<>«.format(address)
# Sending a reply to client
Output:
UDP server up and listening
Message from Client:b»Hello UDP Server»
Client IP Address:(«127.0.0.1», 51696)
Example: UDP Client using Python
msgFromClient = «Hello UDP Server»
serverAddressPort = («127.0.0.1», 20001)
# Create a UDP socket at client side
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Send to server using created UDP socket
msg = «Message from Server <>«.format(msgFromServer[0])
Output:
Message from Server b»Hello UDP Client»
Send and receive UDP packets via Python
We already know about two main transport layer protocols like TCP and UDP. For more information about TCP and UDP you can check reference section. In this article we will learn how to send and receive UDP packets using python program.
Expectations:
Here are some key points can be learned from this article
- Sending some text using python program which uses UDP protocol.
- Receiving some text using python program which uses UDP protocol.
- Check UDP packet in Wireshark.
- Learn about python code to send and receive UDP packets.
General Set Up Diagram:
System A and B should able to ping each other.
Assumptions or Limitations:
- Both systems should be having Linux with Ubuntu. The code may or may not work on other operating system like Windows10, MAC etc.
- Both systems should have python version 3. This code may or may not work on python 2.7 version.
Note: You can check reference for trying out Send and Receive UDP packets via Linux CLI before going for python files to do the same task.
Python files:
There are two python files server.py and client.py. server file and client file should be present in Server system and Client system respectively.
if len ( sys . argv ) == 3 :
# Get «IP address of Server» and also the «port number» from argument 1 and argument 2
ip = sys . argv [ 1 ]
port = int ( sys . argv [ 2 ] )
else :
print ( «Run like : python3 server.py » )
exit ( 1 )
# Create a UDP socket
s = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM )
# Bind the socket to the port
server_address = ( ip , port )
s. bind ( server_address )
print ( «Do Ctrl+c to exit the program !!» )
while True :
print ( «####### Server is listening #######» )
data , address = s. recvfrom ( 4096 )
print ( » \n \n 2. Server received: » , data. decode ( ‘utf-8’ ) , » \n \n » )
send_data = input ( «Type some text to send => » )
s. sendto ( send_data. encode ( ‘utf-8’ ) , address )
print ( » \n \n 1. Server sent : » , send_data , » \n \n » )
if len ( sys . argv ) == 3 :
# Get «IP address of Server» and also the «port number» from argument 1 and argument 2
ip = sys . argv [ 1 ]
port = int ( sys . argv [ 2 ] )
else :
print ( «Run like : python3 client.py » )
exit ( 1 )
# Create socket for server
s = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , 0 )
print ( «Do Ctrl+c to exit the program !!» )
# Let’s send data through UDP protocol
while True :
send_data = input ( «Type some text to send =>» ) ;
s. sendto ( send_data. encode ( ‘utf-8’ ) , ( ip , port ) )
print ( » \n \n 1. Client Sent : » , send_data , » \n \n » )
data , address = s. recvfrom ( 4096 )
print ( » \n \n 2. Client received : » , data. decode ( ‘utf-8’ ) , » \n \n » )
# close the socket
s. close ( )
Send/Receive UDP packet:
Let’s take an example like we will send UDP packet from System A to System B. So, in server-client concept, we have to run server at System B side and client at System A side.
Also we have valid IP addresses.
Now unlike Send and Receive UDP packets via Linux CLI we will run server.py in System, B [192.168.1.102] and then we will run client.py in System A [192.168.1.6].
How to run server.py in 192.168.1.102?
Here is the command to run server.py
Here is the screenshot
Here there are two arguments for the python program. 1 st argument is IP address of server itself , here its 192.168.1.102 and 2 nd argument is port which server will be listening, here we have chosen 4444.
How to run client.py in 192.168.1.6?
Here is the command to run client.py
Here is the screenshot
Here there are two arguments for the python program. 1 st argument is IP address of server , here its 192.168.1.102 and 2 nd argument is port where server is running. For our example it’s 4444.
Send or receive some text:
Now as you can see we are ready to communicate between two systems. But we need to start from client first. Let’s type something in client and see if it reaches to server or not.
Send Data from client: “I am from Client”
Screenshot form client:
Now this client message should come to server. Here is the server screenshot.
Now we can see in server side also we have option to send something to client. Let’s try that.
Send Data from client: “I am from Server”
Server screenshot:
And here is the screenshot on client side.
Now this will go on infinite times until we stop the python program using Ctrl+c.
Check UDP packet in Wireshark:
Now we have done some communication but how do we come to know that UDP was used to send or receive those packets. So, we can check capture in Wireshark.
Let’s see the packet when client [192.168.1.6] sent data [“I am from Client”] to server [192.168.1.6].
Code explanation:
For basic python code explanation refer “Python Socket File Transfer Send” in reference section.
We will only explain important lines codes for Client and Server python file. There are useful comments inside the client and server code.
Client code explanation:
The above line is required to check whether user has passed required mandatory arguments. Or else program will exit. Same check is there in server program.
The above line is to create socket server with UDP [SOCK_DGRAM] protocol. Same code is there in server.py.
To run program in infinite loop until user does Ctrl+c. Same code is there in server.py.
To send data for mentioned ip and port number.
To receive any data coming from server. Same code is there in server.py.
Server code explanation:
Send data to client address.
Conclusion:
We can send or receive UDP data using python program. Internally it uses server client mechanism.
References:
About the author
Bamdeb Ghosh
Bamdeb Ghosh is having hands-on experience in Wireless networking domain.He’s an expert in Wireshark capture analysis on Wireless or Wired Networking along with knowledge of Android, Bluetooth, Linux commands and python. Follow his site: wifisharks.com
RELATED LINUX HINT POSTS
Linux Hint LLC, editor@linuxhint.com
1309 S Mary Ave Suite 210, Sunnyvale, CA 94087
Privacy Policy and Terms of Use