How to Send a UDP Packet in Python

Recently, I ran across a problem where I wanted to automate the testing of a microcontroller for which I was unable to modify the locked down embedded software. Moreover, the microcontroller could only communicate over an Ethernet network using TCP/IP and UDP. Sending either a TCP or UDP packet onto a network is a very easy thing to do using Python, but takes a little bit of knowledge about networking for it to make sense. In this tutorial I am going to give the most bare-bones and simplest possible way to send a packet of data over a network using UDP.

  1. Sending a UDP Packet
  2. Handling Basic Exceptions

Return to Top

Sending a UDP Packet

So, without beating around the bush, here is how to send a UDP packet.

Pretty easy. The only things you would need to change are the IP address you are trying to send the data to (IPADDR), the port number you are trying to send the data to (PORTNUM), and the data you want to put inside the data of the UPD packet (PACKETDATA). Now, you might be wondering what the following code is used for.

This is necessary if you want to input the data to be transmitted as hex (which is usually the case in networking). If you didn’t include that statement, the data would be sent as a string (in a different encoding) instead. This would mean that if you looked at the data portion of your packet in Wireshark, you would see something different than what you put inside the string for PACKETDATA.

Return to Top

Handling Basic Exceptions

Like I said before, this is the most bare-bones way to send a UDP packet over a network. No fancy stuff involved. There is however, one thing that to add that is very helpful. If the socket fails to connect, you will get an exception. One way you can deal with this is to simply ignore any exceptions. This can be done by modifying your UDP script to include a try and except.

So then, your new program will look like the following:

Good luck!

Return to Top

1 Comment How to Send a UDP Packet in Python

  1. Mecano May 16, 2014 at 7:25 am

    Thank you, exactly what i was looking for ^^
    I just changed SOCK_DGRAM by SOCK_STREAM for TCP packet.
    Helpfull 🙂

Leave A Comment

Your email address will not be published.