Search code examples
pythonsocketsudpbroadcasting

Python - Sockets set SO_BROADCAST for one sending


I have a sender class for sending data using sockets:

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)

And I can create an instance of Sender to send data:

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

The problem is that the sender might want to send a broadcast to 255.255.255.255.

Normally for broadcasts I do:

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

The reason this doesn't work here is because my sender might send broadcasts or send messages to ips.

How would I set SO_BROADCAST only when a broadcast is sent without making separate sender classes and instances: Sender, BroadcastSender?

Thanks in advance!


Solution

  • NEW ANSWER

    As @user207421 said:

    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.


    OLD ANSWER

    To allow your socket to send messages to 255.255.255.255 (broadcast) you can do something like this...

    Inside 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)