A Python UDP client is not much different than a TCP client; we need to make only two small changes to get it to send packets in UDP form.
import socket
target_host = "127.0.0.1"
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"AAABBBCCC", (target_host, target_port))
data, addr = client.recvfrom(4096)
print(data.decode())
- As you can see, we change the socket type to
SOCK_DGRAMwhen creating the socket object. - The next step is to simply call
sendto(), passing in the data and the server you want to send the data to. - Because UDP is a connectionless protocol, there is no call to
connect()beforehand. - The last step is to call
recvfrom()to receive UDP data back. - You will also notice that it returns both the data and the details of the remote host and port.
Top comments (0)