Python socket.SO_BROADCAST Examples
The following are 30
code examples of socket.SO_BROADCAST().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
socket
, or try the search function
.
Example #1
Source File: network.py From python-lifx-sdk with MIT License | 7 votes |
def __init__(self, address='0.0.0.0', broadcast='255.255.255.255'): # Prepare a socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.bind((address, 0)) self._socket = sock self._listener = ListenerThread(sock, self._handle_packet) self._listener.start() self._packet_handlers = {} self._current_handler_id = 0 self._broadcast = broadcast
Example #2
Source File: client.py From nukemyluks with Apache License 2.0 | 7 votes |
def send_packet(secret): try: broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) broadcast_socket.bind(('', 0)) broadcast_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) except Exception as err: print "[!] Error creating broadcast socket: %s" % err sys.exit(ERROR) data = "nukemyluks_" + secret try: broadcast_socket.sendto(data, ('<broadcast>', DEFAULT_PORT)) except Exception as err: print "[!] Error sending packet: %s" % err sys.exit(ERROR)
Example #3
Source File: registry.py From NoobSec-Toolkit with GNU General Public License v2.0 | 6 votes |
def discover(self, name): sock = socket.socket(self.sock_family, socket.SOCK_DGRAM) try: if self.bcast: sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) data = brine.dump(("RPYC", "QUERY", (name,))) sock.sendto(data, (self.ip, self.port)) sock.settimeout(self.timeout) try: data, _ = sock.recvfrom(MAX_DGRAM_SIZE) except (socket.error, socket.timeout): servers = () else: servers = brine.load(data) finally: sock.close() return servers
Example #4
Source File: multicast-relay.py From multicast-relay with GNU General Public License v3.0 | 6 votes |
def addListener(self, addr, port, service): if self.isBroadcast(addr): self.etherAddrs[addr] = self.broadcastIpToMac(addr) elif self.isMulticast(addr): self.etherAddrs[addr] = self.multicastIpToMac(addr) else: # unicast -- we don't know yet which IP we'll want to send to self.etherAddrs[addr] = None # Set up the receiving socket and corresponding IP and interface information. # One receiving socket is required per multicast address. rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) rx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) for interface in self.interfaces: (ifname, mac, ip, netmask) = self.getInterface(interface) # Add this interface to the receiving socket's list. if self.isBroadcast(addr): rx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) elif self.isMulticast(addr): packedAddress = struct.pack('4s4s', socket.inet_aton(addr), socket.inet_aton(ip)) rx.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, packedAddress) # Generate a transmitter socket. Each interface # requires its own transmitting socket. if interface not in self.noTransmitInterfaces: tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) tx.bind((ifname, 0)) self.transmitters.append({'relay': {'addr': addr, 'port': port}, 'interface': ifname, 'addr': ip, 'mac': mac, 'netmask': netmask, 'socket': tx, 'service': service}) rx.bind((addr, port)) self.receivers.append(rx)
Example #5
Source File: discovery.py From IDArling with GNU General Public License v3.0 | 6 votes |
def start(self, host, port, ssl): """Start the discovery process and broadcast the given information.""" self._logger.debug("Starting clients discovery") self._info = "%s %d %s" % (host, port, ssl) # Create a datagram socket capable of broadcasting self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self._socket.settimeout(0) # No timeout self._socket.setblocking(0) # No blocking self._read_notifier = QSocketNotifier( self._socket.fileno(), QSocketNotifier.Read, self ) self._read_notifier.activated.connect(self._notify_read) self._read_notifier.setEnabled(True) self._started = True self._timer.start() self._send_request()
Example #6
Source File: mavlink.py From dronekit-python with Apache License 2.0 | 6 votes |
def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, source_component=0, use_native=mavutil.default_native): self._logger = logging.getLogger(__name__) a = device.split(':') if len(a) != 2: self._logger.critical("UDP ports must be specified as host:port") sys.exit(1) self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_server = input self.broadcast = False self.addresses = set() if input: self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.port.bind((a[0], int(a[1]))) else: self.destination_addr = (a[0], int(a[1])) if broadcast: self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.broadcast = True mavutil.set_close_on_exec(self.port.fileno()) self.port.setblocking(False) mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, source_component=source_component, input=input, use_native=use_native)
Example #7
Source File: __init__.py From broadlink-thermostat with GNU General Public License v3.0 | 6 votes |
def __init__(self, host, mac, timeout=10): self.host = host self.mac = mac self.timeout = timeout self.count = random.randrange(0xffff) self.key = bytearray([0x09, 0x76, 0x28, 0x34, 0x3f, 0xe9, 0x9e, 0x23, 0x76, 0x5c, 0x15, 0x13, 0xac, 0xcf, 0x8b, 0x02]) self.iv = bytearray([0x56, 0x2e, 0x17, 0x99, 0x6d, 0x09, 0x3d, 0x28, 0xdd, 0xb3, 0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58]) self.id = bytearray([0, 0, 0, 0]) self.cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.cs.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.cs.bind(('',0)) self.type = "Unknown" self.lock = threading.Lock() if 'pyaes' in sys.modules: self.encrypt = self.encrypt_pyaes self.decrypt = self.decrypt_pyaes else: self.encrypt = self.encrypt_pycrypto self.decrypt = self.decrypt_pycrypto
Example #8
Source File: nmb.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def _setup_connection(self, dstaddr, timeout=None): port = randint(10000, 60000) af, socktype, proto, _canonname, _sa = socket.getaddrinfo(dstaddr, port, socket.AF_INET, socket.SOCK_DGRAM)[0] s = socket.socket(af, socktype, proto) has_bind = 1 for _i in range(0, 10): # We try to bind to a port for 10 tries try: s.bind((INADDR_ANY, randint(10000, 60000))) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) has_bind = 1 except socket.error: pass if not has_bind: raise NetBIOSError, ('Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN) self.__sock = s
Example #9
Source File: discovery.py From bluesky with GNU General Public License v3.0 | 6 votes |
def __init__(self, own_id, is_client=True): self.address = get_ownip() self.broadcast = '255.255.255.255' self.port = settings.discovery_port self.own_id = own_id self.mask = IS_CLIENT if is_client else IS_SERVER # Create UDP socket self.handle = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # Ask operating system to let us do broadcasts from socket self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) if hasattr(socket, 'SO_REUSEPORT'): self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) else: self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind UDP socket to local port so we can receive pings self.handle.bind(('', self.port))
Example #10
Source File: MACServerExploit.py From WinboxPoC with MIT License | 6 votes |
def __init__(self, mac): self.session_bytes_sent = 0 self.session_bytes_recv = 0 self.source_mac = b"\xff\xff\xff\xff\xff\xff" # put mac of your pc if mikrotik is not responding self.dest_mac = mac self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.sock.bind(('', 0)) self.buffer = [] self.work = True self.connected = False self.rm = threading.Thread(target=self.__recv_manager__) self.rm.start() self.__send_init__()
Example #11
Source File: test_discovery.py From networkzero with MIT License | 6 votes |
def test_beacon_already_running(): # # NB this one has to run without the beacon fixture # # Bind a socket on a random port before attempting # to start a beacon on that same port. # port = random.choice(nw0.config.DYNAMIC_PORTS) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind(("", port)) try: assert nw0.discovery._beacon is None nw0.discovery._start_beacon(port=port) assert nw0.discovery._beacon is nw0.discovery._remote_beacon finally: s.close() # # Make sure any future beacon use assumes it's not # already running. # nw0.discovery._stop_beacon()
Example #12
Source File: setupdevice.py From deskcon-desktop with GNU General Public License v3.0 | 6 votes |
def run(self): UDP_IP = "0.0.0.0" UDP_PORT = 5108 sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) while (True): data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes spl = data.split("::") if (spl[0] == "0"): print "received discovery broadcast" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) uuid = str(configmanager.uuid) pairport = str(configmanager.port) hostname = socket.gethostname() data = uuid+"::"+hostname+"::"+pairport s.sendto(data, (addr[0], UDP_PORT))
Example #13
Source File: thread_modules.py From kawaii-player with GNU General Public License v3.0 | 6 votes |
def run(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) port = str(ui.local_port_stream) print(ui.local_ip_stream, '-----ip--', ui.local_port_stream) msg = 'this is kawaii-player At: port={} https={} pc_to_pc_casting={} msg={}'.format( port, ui.https_media_server, ui.pc_to_pc_casting, ui.broadcast_message) msg = bytes(msg , 'utf-8') if ui.https_media_server: https_val = 'https' else: https_val = 'http' subnet_mask = ui.local_ip_stream.rsplit('.', 1)[0] + '.255' notify_msg = '{0}://{1}:{2} started broadcasting. Now Clients can Discover it'.format( https_val, ui.local_ip_stream, ui.local_port_stream) send_notification(notify_msg) print(subnet_mask) while ui.broadcast_server: s.sendto(msg, (subnet_mask,12345)) time.sleep(1) send_notification('Broadcasting Stopped')
Example #14
Source File: ecolab.py From EcoLab with GNU General Public License v2.0 | 6 votes |
def wake_on_lan(mac_address): if len(mac_address) == 12: pass elif len(mac_address) == 12 + 5: sep = mac_address[2] mac_address = mac_address.replace(sep, '') else: raise ValueError('Wrong MAC Address format!') # (EN) Incorrect MAC format! data = ''.join(['FFFFFFFFFFFF', mac_address * 20]) send_data = '' for i in range(0, len(data), 2): send_data = ''.join([send_data, struct.pack('B', int(data[i: i + 2], 16))]) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.sendto(send_data, ('<broadcast>', 7))
Example #15
Source File: ap-ro.py From networking with GNU General Public License v3.0 | 6 votes |
def discover(match="", timeout=2): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.sendto(ssdpre, (ssdpsrc["ip_address"], ssdpsrc["port"])) s.settimeout(timeout) responses = [] print "" try: while True: response = s.recv(1000) if match in response: print response responses.append(response) except: pass return responses
Example #16
Source File: ap-ro.py From networking with GNU General Public License v3.0 | 6 votes |
def reboot(timeout=2): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.sendto(exptpack1, (ssdpsrc["ip_address"], ssdpsrc["port"])) s.settimeout(timeout) s.settimeout(timeout) trg = raw_input("\nTarget: ") tpg = int(input("Port: ")) for i in range(4): sys.stdout.write("\rSending Reboot Payload" + "." * i) time.sleep(0.05) print "" s.sendto(exptpack1, (trg, tpg)) try: s.connect((str(tpg), int(tpg))) time.sleep(0.1) s.send(u"`REBOOT`") s.close() time.sleep(1) s.connect((str(tpg), int(tpg))) except: print "UPnP Device Rebooted" s.close()
Example #17
Source File: DeviceManager.py From ProjectAlice with GNU General Public License v3.0 | 6 votes |
def __init__(self): super().__init__(databaseSchema=self.DATABASE) self._devices = dict() self._broadcastRoom = '' self._broadcastFlag = threading.Event() self._broadcastPort = None self._broadcastTimer = None self._flashThread = None self._listenPort = None self._broadcastSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._broadcastSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self._broadcastSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._listenSocket.settimeout(2)
Example #18
Source File: wol.py From epoptes with GNU General Public License v3.0 | 6 votes |
def wake_on_lan(macaddress): """Power on remote computers using Wake On LAN.""" # Handle MACs with or without separators. if len(macaddress) == 12: pass elif len(macaddress) == 12 + 5: sep = macaddress[2] macaddress = macaddress.replace(sep, '') else: raise ValueError('Incorrect MAC address format') print("Sending magic packet to", macaddress) packet = bytes.fromhex(''.join(['FFFFFFFFFFFF', macaddress * 20])) # Broadcast it to the LAN. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) for brd in get_broadcast_list(): sock.sendto(packet, (brd, 9))
Example #19
Source File: registry.py From NoobSec-Toolkit with GNU General Public License v2.0 | 6 votes |
def discover(self, name): sock = socket.socket(self.sock_family, socket.SOCK_DGRAM) try: if self.bcast: sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) data = brine.dump(("RPYC", "QUERY", (name,))) sock.sendto(data, (self.ip, self.port)) sock.settimeout(self.timeout) try: data, _ = sock.recvfrom(MAX_DGRAM_SIZE) except (socket.error, socket.timeout): servers = () else: servers = brine.load(data) finally: sock.close() return servers
Example #20
Source File: nmb.py From cracke-dit with MIT License | 6 votes |
def _setup_connection(self, dstaddr, timeout=None): port = randint(10000, 60000) af, socktype, proto, _canonname, _sa = socket.getaddrinfo(dstaddr, port, socket.AF_INET, socket.SOCK_DGRAM)[0] s = socket.socket(af, socktype, proto) has_bind = 1 for _i in range(0, 10): # We try to bind to a port for 10 tries try: s.bind((INADDR_ANY, randint(10000, 60000))) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) has_bind = 1 except socket.error: pass if not has_bind: raise NetBIOSError, ('Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN) self.__sock = s
Example #21
Source File: __init__.py From broadlink-thermostat with GNU General Public License v3.0 | 5 votes |
def setup(ssid, password, security_mode): # Security mode options are (0 - none, 1 = WEP, 2 = WPA1, 3 = WPA2, 4 = WPA1/2) payload = bytearray(0x88) payload[0x26] = 0x14 # This seems to always be set to 14 # Add the SSID to the payload ssid_start = 68 ssid_length = 0 for letter in ssid: payload[(ssid_start + ssid_length)] = ord(letter) ssid_length += 1 # Add the WiFi password to the payload pass_start = 100 pass_length = 0 for letter in password: payload[(pass_start + pass_length)] = ord(letter) pass_length += 1 payload[0x84] = ssid_length # Character length of SSID payload[0x85] = pass_length # Character length of password payload[0x86] = security_mode # Type of encryption (00 - none, 01 = WEP, 02 = WPA1, 03 = WPA2, 04 = WPA1/2) checksum = 0xbeaf for i in range(len(payload)): checksum += payload[i] checksum = checksum & 0xffff payload[0x20] = checksum & 0xff # Checksum 1 position payload[0x21] = checksum >> 8 # Checksum 2 position sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.sendto(payload, ('255.255.255.255', 80))
Example #22
Source File: udp.py From learn_python3_spider with MIT License | 5 votes |
def setBroadcastAllowed(self, enabled): """ Set whether this port may broadcast. This is disabled by default. @param enabled: Whether the port may broadcast. @type enabled: L{bool} """ self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, enabled)
Example #23
Source File: wol.py From stash with MIT License | 5 votes |
def send_magic_packet(*macs, **kwargs): """ Wakes the computer with the given mac address if wake on lan is enabled on that host. Keyword arguments: :arguments macs: One or more macaddresses of machines to wake. :key ip_address: the ip address of the host to send the magic packet to (default "255.255.255.255") :key port: the port of the host to send the magic packet to (default 9) """ packets = [] ip = kwargs.pop('ip_address', BROADCAST_IP) port = kwargs.pop('port', DEFAULT_PORT) for k in kwargs: raise TypeError('send_magic_packet() got an unexpected keyword ' 'argument {!r}'.format(k)) for mac in macs: packet = create_magic_packet(mac) packets.append(packet) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.connect((ip, port)) for packet in packets: sock.send(packet) sock.close()
Example #24
Source File: registry.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def register(self, aliases, port, interface = ""): self.logger.info("registering on %s:%s", self.ip, self.port) sock = socket.socket(self.sock_family, socket.SOCK_DGRAM) sock.bind((interface, 0)) try: if self.bcast: sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) data = brine.dump(("RPYC", "REGISTER", (aliases, port))) sock.sendto(data, (self.ip, self.port)) tmax = time.time() + self.timeout while time.time() < tmax: sock.settimeout(tmax - time.time()) try: data, address = sock.recvfrom(MAX_DGRAM_SIZE) rip, rport = address[:2] except socket.timeout: self.logger.warn("no registry acknowledged") return False if rport != self.port: continue try: reply = brine.load(data) except Exception: continue if reply == "OK": self.logger.info("registry %s:%s acknowledged", rip, rport) return True else: self.logger.warn("no registry acknowledged") return False finally: sock.close()
Example #25
Source File: udp.py From learn_python3_spider with MIT License | 5 votes |
def setBroadcastAllowed(self, enabled): """ Set whether this port may broadcast. This is disabled by default. @param enabled: Whether the port may broadcast. @type enabled: L{bool} """ self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, enabled)
Example #26
Source File: udp.py From learn_python3_spider with MIT License | 5 votes |
def getBroadcastAllowed(self): """ Checks if broadcast is currently allowed on this port. @return: Whether this port may broadcast. @rtype: L{bool} """ return operator.truth( self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST))
Example #27
Source File: xiaomi-devices-active.py From HomePWN with GNU General Public License v3.0 | 5 votes |
def run(self): # thanks to python-miio https://github.com/rytilahti/python-miio try: timeout = int(self.args["timeout"]) except: timeout = 5 addrs = [] # To avoid duplicates if str(self.args["rhost"]) != "None": addr = self.args["rhost"] else: addr = '255.255.255.255' print("Sending packets...") helobytes = bytes.fromhex('21310020ffffffffffffffffffffffffffffffffffffffffffffffffffffffff') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.settimeout(timeout) s.sendto(helobytes, (addr, 54321)) while True: try: data, addr = s.recvfrom(1024) token = "" try: #TODO token = str(data[16:]).replace("b'","").replace("'","").replace("\\x","") except: token = "" if addr[0] not in addrs: print_info(f"Xiaomi Device >> {addr[0]} - Token({token})") addrs.append(addr[0]) except socket.timeout: print_ok("Discovery done") break except Exception as ex: print_error(f"Error while reading discover results: {ex}") break
Example #28
Source File: registry.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def unregister(self, port): self.logger.info("unregistering from %s:%s", self.ip, self.port) sock = socket.socket(self.sock_family, socket.SOCK_DGRAM) try: if self.bcast: sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) data = brine.dump(("RPYC", "UNREGISTER", (port,))) sock.sendto(data, (self.ip, self.port)) finally: sock.close()
Example #29
Source File: centry.py From Centry with GNU General Public License v3.0 | 5 votes |
def broadcast_panic(): msg = correct_hash s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 ) s.sendto(msg, ("<broadcast>", 29899 ) ) s.close()
Example #30
Source File: udp.py From learn_python3_spider with MIT License | 5 votes |
def getBroadcastAllowed(self): """ Checks if broadcast is currently allowed on this port. @return: Whether this port may broadcast. @rtype: L{bool} """ return operator.truth( self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST))