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?
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.
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. 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:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With