Socket-broadcast, python实现局域网UDP广播

利用UDP在局域网实现广播并找到相同类型的节点:


1 向局域网发送消息的 sender.py

import math
import json
import random
import socket

sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

PORT = 9999
machineName = socket.getfqdn(socket.gethostname())
machineAddress = socket.gethostbyname(machineName)

message = {
    "ip": machineAddress,
    "random": math.floor(random.random() * 10000)
}

network = ''
sender.sendto(json.dumps(message).encode('utf-8'), (network, PORT))

2 持续监听端口,收到消息后统计有多少相同节点的接收端 receiver.py

import socket

socketReceiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socketReceiver.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

PORT = 9999

socketReceiver.bind(('', PORT))
print('Listening for broadcast at ', socketReceiver.getsockname())

while True:
    data, address = socketReceiver.recvfrom(65535)
    print('Server received from {}:{}'.format(address, data.decode('utf-8')))

 

你可能感兴趣的:(Socket-broadcast, python实现局域网UDP广播)