Programming udp sockets in python

By | October 16, 2012

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 connectionless 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

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

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. Ncat is a telnet alternative that is more powerful and more featureful.

$ 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

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.

Last Updated On : 6th August 2016

Related Post

23 thoughts on “Programming udp sockets in python

  1. nit

    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

  2. ayush

    hey can you correct my code sir…??
    its about 350 lines big……a client side program
    but with very few errors of sockets only

  3. Chaythanya Nair

    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?

    1. psoikjuhdguf3ihojpk-j0ohrigu3vbijk[f

      Hey change localhost to the ip address for example
      host = ‘localhost’;
      to host = ‘192.168.4.33’; this being the ip address

  4. Silverfox

    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.

  5. Nhân

    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???

      1. Nhân

        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() @@

          1. Nhân

            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

          2. Nhân

            it works!!! :)

            But in this Server has other [email protected]@ 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()

          3. Silver Moon

            the last print statement should be

            print (‘Message[‘ + addr[0] + ‘:’ + str(addr[1]) + ‘] – ‘ + data.strip().decode(“utf-8”))

Leave a Reply

Your email address will not be published. Required fields are marked *