Python Forum
Send UDP packet after bind - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Networking (https://python-forum.io/forum-12.html)
+--- Thread: Send UDP packet after bind (/thread-32868.html)



Send UDP packet after bind - pacmyc - Mar-11-2021

I want to send a UDP packet to 192.168.0.155 and then listen for replies on the same port as I sent the packet from.
The below code doesn't work. I can't invoke s.sendto after I have binded the socket.
Any suggestions?


import socket
import sys
ip = "127.0.0.1"
port = 42134
# Create a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
server_address = (ip, port)
s.bind(server_address)
print("Do Ctrl+c to exit the program !!")

send_data = 'B:reglistener'
s.sendto(send_data.encode('utf-8'), ("192.168.0.155", 42314))

while True:
    print("####### Server is listening #######")
    data, address = s.recvfrom(4096)
    print("\n\n 2. Server received: ", data.decode('utf-8'), "\n\n")
    send_data = input("Type some text to send => ")
    s.sendto(send_data.encode('utf-8'), address)
    print("\n\n 1. Server sent : ", send_data,"\n\n")