Python Forum
UDP Listen without Bind()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
UDP Listen without Bind()
#1
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)
Reply
#2
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)
Reply
#3
Thanks for sharing
Reply
#4
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do i listen to loopback address on my local computer, without a port billykid999 6 2,766 May-29-2023, 07:50 PM
Last Post: billykid999
  Listen TCP and send data to websockets neoboby 3 3,002 Feb-13-2023, 09:47 PM
Last Post: Vadanane
  Send UDP packet after bind pacmyc 0 2,627 Mar-11-2021, 10:28 PM
Last Post: pacmyc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020