Python - 套接字设置 SO_BROADCAST 一次发送

Python - Sockets set SO_BROADCAST for one sending

我有一个使用套接字发送数据的发送器class:

import socket as s

class Sender:
    def __init__(self):
        self.socket = s.socket(s.AF_INET, s.SOCK_DGRAM)
        self.socket.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1)

    def send(self, msg, addr):
        self.socket.sendto(msg, addr)

我可以创建一个 Sender 的实例来发送数据:

sender = Sender()
sender.send("Message example", (ip, port))

问题是发件人可能想向 255.255.255.255 发送广播。

通常我做的广播:

self.socket.setsockopt(s.SOL_SOCKET, s.SO_BROADCAST, 1)

这在这里不起作用的原因是因为我的发件人可能会向 ips 发送广播或发送消息。

我如何设置 SO_BROADCAST 仅当发送广播时没有单独的发送者 classes 和实例:SenderBroadcastSender?

提前致谢!

新答案

正如@user207421所说:

Why? Setting it doesn't prevent you from unicasting. Just set it on the socket when you open it. Then you can both unicast and broadcast.


旧答案

要允许您的套接字向 255.255.255.255(广播)发送消息,您可以这样做...

里面 Sender class:

def send(self, msg, addr):
    if addr[0] == "255.255.255.255": self.socket.setsockopt(s.SOL_SOCKET, s.SO_BROADCAST, 1)
    self.socket.sendto(msg, addr)
    if addr[0] == "255.255.255.255": self.socket.setsockopt(s.SOL_SOCKET, s.SO_BROADCAST, 0)