Python Forum

Full Version: UDP Listen without Bind()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need to create a UDP listener without using bind() as other applications also listen to the port on the same device.

The following code works but uses bind(). I've searched for days and just can't find the answer.

I know this can be done but I just don't know how to do it.

Please give my some idea how to solve this.

Thanks,

Gary

import select, socket 

port = 50222  # where do you expect to get a msg?
bufferSize = 1024 # whatever you need

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',port))
s.setblocking(0)

while True:
    result = select.select([s],[],[])
    msg = result[0][0].recv(bufferSize) 
    print (msg)
It was pointed out to me this is the answer.

import socket 

port = 50222  # WeatherFlow Hub port
bufferSize = 1024 # buffer size

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('',port))
s.setblocking(0)

while True:
    result = select.select([s],[],[])
    msg = result[0][0].recv(bufferSize) 
    print (msg)
Thanks for sharing
You can use only a socket, if you bind (TCP/UDP) it to a port or when you connect to somewhere (TCP).
Even when you send a packet via UDP, your Socket will have a local address.
Port 0 is a special port reserved by the operating system.
Bind a socket to port 0, acquires a free random port.

So you still have an open port.
To see, which address and port is used, use the method getsockname() on your socket object.
s.getsockname()
Output:
('0.0.0.0', 45699)
Additional Information: https://www.lifewire.com/port-0-in-tcp-and-udp-818145