我正在编写一个非常简单的局域网服务发现协议.其 idea 是通过UDP向整个局域网广播服务器的连接数据.
我能够将数据从广播者传递给听众,但前提是我使用地址"0.0.0.0".如果我使用本地LAN地址+.255(LAN广播地址)我无法发送任何消息.
这是我广播的代码.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())
这是我的听众.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())
0.0.0.0是广播的正确IP还是我遗漏了什么?