Python Forum
UDP Listen without 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: UDP Listen without Bind() (/thread-9236.html)



UDP Listen without Bind() - GaryFunk - Mar-28-2018

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)



RE: UDP Listen without Bind() - GaryFunk - Mar-29-2018

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)



RE: UDP Listen without Bind() - Larz60+ - Mar-29-2018

Thanks for sharing


RE: UDP Listen without Bind() - DeaD_EyE - Mar-29-2018

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