udp发送广播消息

时间:2021-08-15 10:08:17
import socket

if __name__ == '__main__':
    # 创建udpsocket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 设置socket选项, 开启发送广播消息的功能
    # 1. SOL_SOCKET:当前socket
    # 2. SO_BROADCAST: 广播选项
    # 3. True:开启发送广播消息功能
    udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
    # 192.168.131.255: 只给131网段发送广播消息
    # 255.255.255.255: 发送广播消息不区分网段
    # 发送广播消息
    udp_socket.sendto("大家好,我是小汪,多多关照!".encode("gbk"), ("255.255.255.255", 2425))
    # 关闭socket
    udp_socket.close()