Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python send UDP packet

Tags:

python

sockets

I am trying to write a program to send UDP packets, as in https://wiki.python.org/moin/UdpCommunication The code appears to be in Python 2:

import socket  UDP_IP = "127.0.0.1" UDP_PORT = 5005 MESSAGE = "Hello, World!"  print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "message:", MESSAGE  sock = socket.socket(socket.AF_INET, # Internet              socket.SOCK_DGRAM) # UDP sock.sendto(MESSAGE, (UDP_IP, UDP_PORT)) 

If I put parenthesis around the printed stuff, it just prints it on the screen.

What do I need to do to make this work?

like image 560
user2059619 Avatar asked Sep 11 '13 14:09

user2059619


People also ask

How do you send and receive UDP packets?

To receive packets from all the sending hosts, specify the remote IP address as 0.0. 0.0 . Match the port number specified in the Local IP Port parameter with the remote port number of the sending host. You can choose to receive the UDP packets in blocking or non-blocking mode.


2 Answers

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)) 
like image 96
Manoj Pandey Avatar answered Sep 19 '22 19:09

Manoj Pandey


Your code works as is for me. I'm verifying this by using netcat on Linux.

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

  • IP: 127.0.0.1
  • Port: 5005
  • Protocol: UDP

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

[9:34am][wlynch@watermelon ~] nc -ul 127.0.0.1 5005 Hello, World! 
like image 27
Bill Lynch Avatar answered Sep 21 '22 19:09

Bill Lynch