下一个代码发送广播包(在本地Wireshark中检查):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
reqdata = struct.pack('<l', 0x01)
s.sendto( reqdata, ( '192.168.1.255', port ))
但是当我写&#34;广播&#34;在尖括号而不是常量子网广播中,不发送包:
s.sendto( reqdata, ( '<broadcast>', port ))
环境:
ActivePython 2.7.5.6(ActiveState Software Inc.)
上的[MSC v.1500 32位(英特尔)]
基于Python 2.7.5(默认,2013年9月16日,23:16:52)
在win32&#34;
答案 0 :(得分:0)
Python支持'<broadcast>'
,请参阅socket — Low-level networking interface
但是,您可以使用 ipaddress 包
获取网络设备的广播掩码import ipaddress
import socket
netmask = '255.255.255.0' # Netmask is to decode network and host addresses
ip = socket.gethostbyname(socket.gethostname()) # Obtain your IP address
net = ipaddress.IPv4Network(ip + '/' + netmask, False)
broadcast = str(net.broadcast_address)
print('My broadcast address =', broadcast)