I'm writing a very simple service discovery protocol over LAN. The idea is to broadcast to the entire LAN via UDP the connection data of the server.
I am able to pass data from my broadcaster to my listener, but only if I use the address '0.0.0.0'. If I use the local LAN address + .255 (the LAN broadcast address) I cannot send any message.
This is the code of my broadcast.py:
import asyncio
import asyncudp
from socket import gethostbyname, gethostname
def getBroadcastIp():
ip = gethostbyname(gethostname())
broadcast_ip = '.'.join(ip.split('.')[:-1]+["255"])
print(broadcast_ip)
# return broadcast_ip
return '0.0.0.0'
async def broadcastUdp():
bip = getBroadcastIp()
while True:
sock = await asyncudp.create_socket(remote_addr=(bip, 50000))
print("Sending MESSAGE")
sock.sendto(b'Message', addr=(bip, 50000))
await asyncio.sleep(3)
sock.close()
async def main():
await asyncio.gather(*[
# I have more stuff here
asyncio.create_task(broadcastUdp())
])
asyncio.run(main())
and this is my listener.py:
import asyncio
import asyncudp
from socket import gethostbyname, gethostname
def getBroadcastIp():
ip = gethostbyname(gethostname())
broadcast_ip = '.'.join(ip.split('.')[:-1]+["255"])
print(broadcast_ip)
# return broadcast_ip
return '0.0.0.0'
async def listenUdp():
bip = getBroadcastIp()
sock = await asyncudp.create_socket(local_addr=(bip, 50000))
try:
while True:
data, addr = await asyncio.wait_for(sock.recvfrom(), 10)
print("RECEIVING: ", data)
except asyncio.TimeoutError:
print('No data received in 10 seconds.')
sock.close()
async def main():
await asyncio.gather(*[
# I have more stuff here
asyncio.create_task(listenUdp())
])
asyncio.run(main())
Is 0.0.0.0 the right IP for broadcasting or am I missing something else?