sockets – Python send UDP packet

sockets – Python send UDP packet

With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a plain string and not bytes. Try this:

print(UDP target IP:, UDP_IP)
print(UDP target port:, UDP_PORT)
print(message:, MESSAGE)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, utf-8), (UDP_IP, UDP_PORT))

Your code works as is for me. Im verifying this by using netcat on Linux.

Using netcat, I can do nc -ul 5005 which will listen for packets at:

  • IP:
  • Port: 5005
  • Protocol: UDP

That being said, heres the output that I see when I run your script, while having netcat running.

[9:34am][[email protected] ~] nc -ul 5005
Hello, World!

sockets – Python send UDP packet

If you are running python 3 then you need to change the print statements to print functions, i.e. put things in brackets () after print statements.

The only thing that you will see the above do is the prints unless you have something listening on port 5005 as you are sending a packet not receiving it – so you need to implement and start the other part of the example in another console window first so it is waiting for the message.

Leave a Reply

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