UDP sockets
UDP or user datagram protocol is an alternative protocol to its more common counterpart TCP. UDP like TCP is a protocol for packet transfer from 1 host to another, but has some important differences.
UDP is a connection-less and non-stream oriented protocol. It means a UDP server just catches incoming packets from any and many hosts without establishing a reliable pipe kind of connection.
In this article we are going to see how to use UDP sockets in python. It is recommended that you also learn about programming tcp sockets in python.
Create UDP sockets
A udp socket is created like this
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
The SOCK_DGRAM specifies datagram (udp) sockets.
Sending and Receiving data on UDP
Since udp sockets are non connected sockets, communication is done using the socket functions sendto and recvfrom.
These 2 functions dont require the socket to be connected to some peer. They just send and receive directly to and from a given address
Udp Server Code
The simplest form of a UDP server can be written in a few lines
import socket port = 5000 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", port)) print "waiting on port:", port while 1: data, addr = s.recvfrom(1024) print data
A udp server has to open a socket and receive incoming data. There is no listen or accept. Run the above server from a terminal and then connect to it using ncat.
Testing with Netcat
Ncat is a telnet alternative that has more features and can connect to UDP ports.
$ ncat localhost 5000 -u -v Ncat: Version 6.00 ( http://nmap.org/ncat ) Ncat: Connected to 127.0.0.1:5000. hello ok
The u flag indicates the udp protocol. Whatever message we send, should display on the server terminal.
Lets write a complete echo server now.
''' Simple udp socket server ''' import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port # Datagram (udp) socket try : s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print 'Socket created' except socket.error, msg : print 'Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() # Bind socket to local host and port try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' #now keep talking with the client while 1: # receive data from client (data, addr) d = s.recvfrom(1024) data = d[0] addr = d[1] if not data: break reply = 'OK...' + data s.sendto(reply , addr) print 'Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + data.strip() s.close()
The above will program will start a udp server on port 8888. Run the program in a terminal. To test the program open another terminal and use the netcat utility to connect to this server. Here is an example
$ ncat -vv localhost 8888 -u Ncat: Version 5.21 ( http://nmap.org/ncat ) Ncat: Connected to 127.0.0.1:8888. hello OK...hello how are you OK...how are you
Use ncat again to send messages to the udp server and the udp server replies back with "OK..." prefixed to the message.
The server terminal also displays the details about the client
$ python server.py Socket created Socket bind complete Message[127.0.0.1:46622] - hello Message[127.0.0.1:46622] - how are you
It is important to note that unlike a tcp server, a udp server can handle multiple clients directly since there is no connection.
It can receive from any client and send the reply. No threads, select polling etc is needed like in tcp servers.
Udp client code
Now that our server is done, its time to code the udp client. It connects to the udp server just like netcat did above.
''' udp socket client Silver Moon ''' import socket #for sockets import sys #for exit # create dgram udp socket try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error: print 'Failed to create socket' sys.exit() host = 'localhost'; port = 8888; while(1) : msg = raw_input('Enter message to send : ') try : #Set the whole string s.sendto(msg, (host, port)) # receive data from client (data, addr) d = s.recvfrom(1024) reply = d[0] addr = d[1] print 'Server reply : ' + reply except socket.error, msg: print 'Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit()
The client will connect to the server and exchange messages like this
$ python simple_client.py Enter message to send : hello Server reply : OK...hello Enter message to send : how are you Server reply : OK...how are you Enter message to send :
Overall udp protocol is simple to program, keeping in mind that it has no notion of connections but does have ports for separating multiple udp applications. Data to be transferred at a time should be send in a single packet.
Pingback: Controlling drivers with data received via TCP/UDP – GrindSkills
Great code. It works. Thanks It helped me a lot.
could some one can help me in writing UDP proxy in python which can do man in the middle between two ethernet ports
Thank you!
That clears my lot of doubts :)
hi,
in udp server
i have 2 clients c1 and c2
when i send from msg from c1 to c2
c2 msg is send to him
but the msg is published to c1 itself what can be done
plz help
Thank you for the basic, quick sample!
hey can you correct my code sir…??
its about 350 lines big……a client side program
but with very few errors of sockets only
how can i broadcast the message to all clients when they are connected to this server ???
hey.. nice tutorial but this doesnt work for a client and server running in two different systems shared over a wifi. should we change the protocol for doing the same?
Hey change localhost to the ip address for example
host = ‘localhost’;
to host = ‘192.168.4.33’; this being the ip address
Great article :)
Would your code run for python 3.x (after normal changes like print())???
It works for python 3.x after you change the print and using encode() and decode() on the strings
I am running your first simple block of code at the top of this tutorial in the python IDE, I also tried it through a terminal, both on win7. The code runs fine, but when I try to connect via telnet, ncat or putty, I get the following:
On windows telnet I get this error: ‘Could not open connection to the host, on port (tried lots), connect failed…’
with ncat I get: ‘ An existing connection was forcibly closed by the remote host. .’
and with putty I get: ‘Network error: connection refused’
I’m confused…
Also, I went through your tcp socket tutorial, and that all worked correctly. Any help much appreciated.
I’m getting the same error here, any advice?
Both protocols, Telnet and SSH work on TCP.
msg = raw_input(‘Enter message to send : ‘)
Sorry, when i run it, it has a problem with “raw_input” like that:”NameError: name ‘raw_input’ is not defined”
What’s statement you define it in your source???
are you using python version 3 ?
In python 3 raw_input has been renamed to input. So use input.
or define raw_input like this
raw_input = input
Thank a lot. I try to using python 3.3 with your project.
Can i import it from 2.x to 3.x with this project.
When it run, it has a problem:
s.sendto(msg, (host, port))
TypeError: ‘str’ does not support the buffer interface
I think it’s wrong in s.sendto() @@
Yeah, it should be easy to port the program to python 3+
Check out the following page
http://docs.python.org/dev/whatsnew/3.0.html
You have to do a couple of changes like wrapping print statements in brackets like a function etc.
There is only some syntax change to be done.
I change it :
import socket #for sockets
import sys #for exit
# create dgram udp socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print (‘Failed to create socket’)
sys.exit()
host = ‘localhost’;
port = 8888;
while(1) :
msg = input(‘Enter message to send : ‘)
try :
#Set the whole string
s.sendto((msg, (host, port)))
# receive data from client (data, addr)
d = s.recvfrom(1024)
reply = d[0]
addr = d[1]
print (‘Server reply : ‘ + reply)
except (socket.error, msg):
print (‘Error Code : ‘ + str(msg[0]) + ‘ Message ‘ + msg[1])
sys.exit()
is that true?? but it doesn’t work @Silver Moon
this should work
https://gist.github.com/silv3rm00n/5678933
it works!!! :)
But in this Server has other problem@@ I’m so sorry, because i’m a newbie
Created on 30-05-2013
@author: ASPIRE 5755G
”’
”’
Simple udp socket server
Silver Moon ([email protected])
”’
import socket
import sys
HOST = ” # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
# Datagram (udp) socket
try :
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print (‘Socket created’)
except socket.error as msg :
print (‘Failed to create socket. Error Code : ‘ + str(msg[0]) + ‘ Message ‘ + msg[1])
sys.exit()
# Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print (‘Bind failed. Error Code : ‘ + str(msg[0]) + ‘ Message ‘ + msg[1])
sys.exit()
print (‘Socket bind complete’)
#now keep talking with the client
while 1:
# receive data from client (data, addr)
d = s.recvfrom(1024)
data = d[0]
addr = d[1]
if not data:
break
reply = ‘OK…’ + data.decode(“utf-8”)
s.sendto(reply.encode(“utf-8”) , addr)
print (‘Message[‘ + addr[0] + ‘:’ + str(addr[1]) + ‘] – ‘ + data.strip())
s.close()
the last print statement should be
print (‘Message[‘ + addr[0] + ‘:’ + str(addr[1]) + ‘] – ‘ + data.strip().decode(“utf-8”))
Thank a lot!!! It works !!
You’re a good one!!! Thank again!!!