Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - UDP client

I am currently reading a Python book and came across the following example:

import socket
target_host = "127.0.0.1"
target_port = 80

# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# send some data
client.sendto("AAABBBCCC",(target_host,target_port))

# receive some data
data, addr = client.recvfrom(4096)

print data

If I understood it right, I am building a listener to my own loop-back IP address on the UDP port 80. My question is, what is it good for and how I can "test" it? (Meaning how can I read the sent "AAABBBCCC")?

Thanks

like image 753
Kaguei Nakueka Avatar asked Aug 03 '26 20:08

Kaguei Nakueka


2 Answers

You need to run a server to listen on the port your sender sent to. there is a good explanation here.

A nice example for you is (based on the above link):

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 80

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

while True:
   data, addr = sock.recvfrom(1024) #buffer of 1024 bytes
   print "received message: ", data

You need to run the server first so it start listening and than run your client separately.

like image 161
Gal Dreiman Avatar answered Aug 05 '26 10:08

Gal Dreiman


If you just want to validate the original server is working and don't need the destination server to be in python, netcat can do this really succinctly from the command line.

nc -ul 80

like image 22
proto_khal Avatar answered Aug 05 '26 09:08

proto_khal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!