Python socket.SO_BROADCAST() Examples

The following are 60 code examples for showing how to use socket.SO_BROADCAST(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: python-lifx-sdk   Author: smarthall   File: network.py    License: MIT License 6 votes vote down vote up
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
Project: dronekit-python   Author: dronekit   File: mavlink.py    License: Apache License 2.0 6 votes vote down vote up
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 3
Project: nukemyluks   Author: juliocesarfort   File: client.py    License: Apache License 2.0 6 votes vote down vote up
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 4
Project: CVE-2017-7494   Author: joxeankoret   File: nmb.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Project: networkzero   Author: tjguk   File: test_discovery.py    License: MIT License 6 votes vote down vote up
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 6
Project: epoptes   Author: epoptes   File: wol.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 7
Project: cracke-dit   Author: eth0izzle   File: nmb.py    License: MIT License 6 votes vote down vote up
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 8
Project: deskcon-desktop   Author: screenfreeze   File: setupdevice.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 9
Project: kawaii-player   Author: kanishka-linux   File: thread_modules.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 10
Project: EcoLab   Author: jfomu   File: ecolab.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 11
Project: networking   Author: RussianOtter   File: ap-ro.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 12
Project: networking   Author: RussianOtter   File: ap-ro.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 13
Project: ProjectAlice   Author: project-alice-assistant   File: DeviceManager.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 14
Project: NoobSec-Toolkit   Author: krintoxi   File: registry.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 15
Project: NoobSec-Toolkit   Author: krintoxi   File: registry.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 16
Project: WinboxPoC   Author: BasuCert   File: MACServerExploit.py    License: MIT License 6 votes vote down vote up
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 17
Project: bluesky   Author: TUDelft-CNS-ATM   File: discovery.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 18
Project: broadlink-thermostat   Author: ralphm2004   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 19
Project: IDArling   Author: IDArlingTeam   File: discovery.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 20
Project: MicroWebSrv2   Author: jczic   File: XAsyncSockets.py    License: MIT License 5 votes vote down vote up
def Create(asyncSocketsPool, localAddr=None, recvBufLen=4096, broadcast=False) :
        try :
            udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        except :
            raise XAsyncUDPDatagramException('Create : Cannot open socket (no enought memory).')
        if broadcast :
            udpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        openRecv = (localAddr is not None)
        if openRecv :
            try :
                udpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                udpSocket.bind(localAddr)
            except :
                raise XAsyncUDPDatagramException('Create : Error to binding the UDP Datagram local address.')
            try :
                size        = max(256, recvBufLen)
                recvBufSlot = XBufferSlot(size=size, keepAlloc=False)
            except :
                raise XAsyncUDPDatagramException('Create : Out of memory?')
        else :
            recvBufSlot = None
        xAsyncUDPDatagram = XAsyncUDPDatagram(asyncSocketsPool, udpSocket, recvBufSlot)
        if openRecv :
            asyncSocketsPool.NotifyNextReadyForReading(xAsyncUDPDatagram, True)
        return xAsyncUDPDatagram

    # ------------------------------------------------------------------------ 
Example 21
Project: lifx-python   Author: sharph   File: network.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def connect():
    global connection, site, targetaddr
    udpsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udpsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    udpsock.bind((IP, PORT))
    p = packetcodec.Packet(packetcodec.GetPANGatewayPayload())
    for x in range(5):
        udpsock.sendto(p.__bytes__(), (BCAST, PORT))
    while True:
        data, addr = udpsock.recvfrom(1024)
        packet = packetcodec.decode_packet(data)
        if packet is not None and \
                isinstance(packet.payload, packetcodec.PANGatewayPayload):
            break
    #udpsock.close()
    if debug:
        print( 'found light: %s' % (addr[0], ))
    #tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #tcpsock.settimeout(2.0)
    #tcpsock.connect(addr)
    #connection = tcpsock
    targetaddr = addr
    udpsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 0)
    udpsock.settimeout(0.1)
    connection = udpsock
    site = packet.site
    if debug:
        print( 'connection established with %s' % (unicode(hexlify(site),
                                                      encoding='utf-8'))) 
Example 22
Project: multicast-relay   Author: alsmith   File: multicast-relay.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 23
Project: nukemyluks   Author: juliocesarfort   File: server.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    # check if we're running this code on Linux or not
    if 'Linux' not in platform.system():
        print "[!] Error: this can only run on Linux."
        sys.exit(ERROR)
    
    # create a broadcast UDP receving socket
    receiving_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    receiving_socket.bind(('<broadcast>', DEFAULT_PORT))
    receiving_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    receiving_socket.setblocking(0)
    
    while True:
        result = select.select([receiving_socket], [], [])
        msg = result[0][0].recv(1024)
        
        if msg.startswith("nukemyluks_"):            
            try:
                configparser = ConfigParser.ConfigParser()
                configparser.read('config.ini')
                hashed_secret = configparser.get('config', 'password_hash')
            except Exception as err:
                print "[!] Error reading config file: %s" % err
                # TODO: send error message back containing the server IP
                sys.exit()
            
            secret = base64.b64decode(msg[len("nukemyluks_"):])
            
            if hashed_secret == hashpw(secret, hashed_secret):
                if not os.path.isfile(NUKEMYLUKS_CMD):
                    print "[!] Cannot execute the %s (No such file)" % NUKEMYLUKS_CMD
                    sys.exit(ERROR)

                cmd_output = Popen([NUKEMYLUKS_CMD], stdout=PIPE,
                                   stdin=PIPE, stderr=PIPE)
                STDOUT, STDERR = cmd_output.communicate()
                print STDOUT
                # TODO: send a success message back containing the server IP 
Example 24
Project: plugin.video.emby   Author: MediaBrowser   File: connection_manager.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _server_discovery(self):
        
        MULTI_GROUP = ("<broadcast>", 7359)
        MESSAGE = "who is EmbyServer?"
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(1.0) # This controls the socket.timeout exception
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.SO_REUSEADDR, 1)
        
        LOG.debug("MultiGroup      : %s", str(MULTI_GROUP))
        LOG.debug("Sending UDP Data: %s", MESSAGE)
        servers = []

        try:
            sock.sendto(MESSAGE, MULTI_GROUP)
        except Exception as error:
            LOG.error(error)

            return servers

        while True:
            try:
                data, addr = sock.recvfrom(1024) # buffer size
                servers.append(json.loads(data))
            
            except socket.timeout:
                LOG.info("Found Servers: %s", servers)

                return servers
            
            except Exception as e:
                LOG.error("Error trying to find servers: %s", e)

                return servers 
Example 25
Project: BiblioPixel   Author: ManiacalLabs   File: network_udp.py    License: MIT License 5 votes vote down vote up
def _connect(self):
        try:
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            if self._broadcast:
                self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

            return self._sock
        except socket.gaierror:
            error = "Unable to connect to or resolve host: {}".format(
                self._host)
            log.error(error)
            raise IOError(error) 
Example 26
Project: pyuavcan   Author: UAVCAN   File: _ipv4.py    License: MIT License 5 votes vote down vote up
def make_output_socket(self, remote_node_id: typing.Optional[int], remote_port: int) -> socket.socket:
        if self.local_node_id is None:
            raise pyuavcan.transport.OperationNotDefinedForAnonymousNodeError(
                f'Anonymous UDP/IP nodes cannot emit transfers, they can only listen. '
                f'The local IP address is {self._local}.'
            )

        bind_to = self._local.host_address
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setblocking(False)
        try:
            # Output sockets shall be bound, too, in order to ensure that outgoing packets have the correct
            # source IP address specified. This is particularly important for localhost; an unbound socket
            # there emits all packets from 127.0.0.1 which is certainly not what we need.
            s.bind((str(bind_to), 0))  # Bind to an ephemeral port.
        except OSError as ex:
            if ex.errno == errno.EADDRNOTAVAIL:
                raise pyuavcan.transport.InvalidMediaConfigurationError(
                    f'Bad IP configuration: cannot bind output socket to {bind_to} [{errno.errorcode[ex.errno]}]'
                ) from None
            raise  # pragma: no cover

        # Specify the fixed remote end. The port is always fixed; the host is unicast or broadcast.
        if remote_node_id is None:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            s.connect((str(self._local.broadcast_address), remote_port))
        elif 0 <= remote_node_id < self._max_nodes:
            ip = IPv4Address(int(self._local.subnet_address) + remote_node_id)
            assert ip in self._local
            s.connect((str(ip), remote_port))
        else:
            raise ValueError(f'Cannot map the node-ID value {remote_node_id} to an IP address. '
                             f'The range of valid node-ID values is [0, {self._max_nodes})')

        _logger.debug('%r: New output socket %r connected to remote node %r, remote port %r',
                      self, s, remote_node_id, remote_port)
        return s 
Example 27
Project: aiotuya   Author: frawau   File: provision.py    License: MIT License 5 votes vote down vote up
def connection_made(self, transport: aio.transports.DatagramTransport):
        #log.debug('started')
        self.transport = transport
        sock = transport.get_extra_info("socket")  # type: socket.socket
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.loop.create_task(self._provision_devices()) 
Example 28
Project: hysen   Author: mairas   File: climate.py    License: Apache License 2.0 5 votes vote down vote up
def broadlink_hysen_climate_device_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 b in payload:
        checksum = (checksum + b) & 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))
    sock.close() 
Example 29
Project: networkzero   Author: tjguk   File: send_bcast.py    License: MIT License 5 votes vote down vote up
def run(message=""):
    if not message:
        message = input("Message: ")
    bmessage = message.encode("utf-8")
    
    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)
    
    while True:
        s.sendto(bmessage, ('192.168.1.255', 53005))
        time.sleep(1) 
Example 30
Project: pyvisa-py   Author: pyvisa   File: rpc.py    License: MIT License 5 votes vote down vote up
def connect(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) 
Example 31
Project: Mr.SIP   Author: meliht   File: sip_packet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_packet(self):
        try:
            f = open(os.path.join(self.method_location, "{0}.message".format(self.method)), "r")
            packet_data = f.read()
            packet_data = self.fill_packet_data(packet_data)

            if self.protocol == "socket":
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.settimeout(5)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
                s.connect((str(self.server_ip), int(self.server_port)))
                s.sendall(packet_data)
                if self.wait:
                    buff,srcaddr = s.recvfrom(8192)
                    s.close()
                    status = self.getResponse(buff)
                    return {"status": True, "response": status}
                else:
                    s.close()
                    return {"status": True}

            elif self.protocol == "scapy":
                pkt = IP(src=self.client_ip, dst=self.server_ip) / UDP(sport=int(self.client_port), dport=int(self.server_port)) / packet_data
                send(pkt, iface=conf.iface)
                return {"status": True}
        except:
            return {"status": False} 
Example 32
Project: Safejumper-for-Desktop   Author: proxysh   File: udp.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 33
Project: Safejumper-for-Desktop   Author: proxysh   File: udp.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 34
Project: Safejumper-for-Desktop   Author: proxysh   File: udp.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 35
Project: Safejumper-for-Desktop   Author: proxysh   File: udp.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 36
Project: Chimay-Red   Author: seekintoo   File: utils.py    License: MIT License 5 votes vote down vote up
def mndp_scan():
    """

    :return:
    """
    cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    cs.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    cs.bind(('', 5678))

    cs.sendto(b'\0\0\0\0', ('255.255.255.255', 5678))

    try:
        entries = {}
        while True:
            (data, src_addr) = cs.recvfrom(1500)
            # ignore the msg we getourselves or if bad
            if data == b'\0\0\0\0' or len(data) < 18:
                continue
            else:
                entry = parse_mndp(data)

            if not entries.get(entry['mac']):
                yield {src_addr[0]: entry}
    finally:
        cs.close() 
Example 37
Project: cloudbase-init   Author: cloudbase   File: dhcp.py    License: Apache License 2.0 5 votes vote down vote up
def get_dhcp_options(dhcp_host=None, requested_options=[], timeout=5.0,
                     vendor_id='cloudbase-init', max_bind_attempts=10,
                     bind_retry_interval=3):
    id_req = random.randint(0, 2 ** 32 - 1)
    options = None

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if not dhcp_host:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    try:
        _bind_dhcp_client_socket(s, max_bind_attempts, bind_retry_interval)

        s.settimeout(timeout)

        local_ip_addr = network.get_local_ip(dhcp_host)
        mac_address = _get_mac_address_by_local_ip(local_ip_addr)

        data = _get_dhcp_request_data(id_req, mac_address, requested_options,
                                      vendor_id)

        s.sendto(data, (dhcp_host or "<broadcast>", 67))

        start = datetime.datetime.now()
        now = start
        replied = False
        while (not replied and
                now - start < datetime.timedelta(seconds=timeout)):
            data = s.recv(1024)
            (replied, options) = _parse_dhcp_reply(data, id_req)
            now = datetime.datetime.now()
    except socket.timeout:
        pass
    finally:
        s.close()

    return options 
Example 38
Project: smarthome   Author: smarthomeNG   File: network.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_wol(mac, ip='255.255.255.255'):
        """
        Sends a wake on lan packet to the given mac address using ipv4 broadcast (or directed to specific ip)

        :param mac: Mac address to wake up (pure numbers or with any separator)
        :type mac: string
        """
        logger = logging.getLogger(__name__)
        if len(mac) == 12:
            pass
        elif len(mac) == 12 + 5:
            mac = mac.replace(mac[2], '')
        else:
            logger.error('Incorrect MAC address format')
            return

        data = ''.join(['FFFFFFFFFFFF', mac * 16])
        send_data = b''
        for i in range(0, len(data), 2):
            send_data = b''.join([send_data, struct.pack('B', int(data[i: i + 2], 16))])

        for _ in range(15):
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            sock.sendto(send_data, (ip, 9))
        logger.debug('Sent WOL packet to {}'.format(mac)) 
Example 39
Project: NintendoClients   Author: Kinnay   File: socket.py    License: MIT License 5 votes vote down vote up
def __init__(self, sock=None):
		self.s = sock
		if not self.s:
			sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
			sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
			self.s = SocketWrapper(sock) 
Example 40
Project: tvalacarta   Author: tvalacarta   File: nmb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, servport = NETBIOS_NS_PORT):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.bind(( INADDR_ANY, 0 ))
            s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        except socket.error, ex:
            s.close()
            raise NetBIOSError, ex 
Example 41
Project: AlexaControlledSamsungTV   Author: eclair4151   File: pywakeonlan.py    License: MIT License 5 votes vote down vote up
def send_magic_packet(*macs, **kwargs):
    """
    Wake up computers having any of the given mac addresses.
    Wake on lan must be enabled on the host device.
    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 42
Project: dnxfirewall-cmd   Author: DOWRIGHTTV   File: dhcp_server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def listener_sock(self):
        l_sock = socket(AF_INET, SOCK_DGRAM)
        l_sock.setsockopt(SOL_SOCKET, SO_REUSEADDR,1)
        l_sock.setsockopt(SOL_SOCKET, SO_BROADCAST,1)
        l_sock.setsockopt(SOL_SOCKET, SO_BINDTODEVICE, f'{self._intf}\0'.encode('utf-8'))
        l_sock.bind((str(INADDR_ANY), PROTO.DHCP_SVR))

        return l_sock 
Example 43
Project: linux-show-player   Author: FrancescoCeruti   File: discovery.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super().__init__(daemon=True)
        # Create UDP socket
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
        self._socket.bind((IP, PORT))

        self._running = True 
Example 44
Project: linux-show-player   Author: FrancescoCeruti   File: discovery.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self.discovered = Signal()

        # Create UDP socket
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)

        self._running = True
        self._cache = [] 
Example 45
Project: NoobSec-Toolkit   Author: krintoxi   File: registry.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 46
Project: NoobSec-Toolkit   Author: krintoxi   File: registry.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 47
Project: NoobSec-Toolkit   Author: krintoxi   File: registry.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 48
Project: stash   Author: ywangd   File: wol.py    License: MIT License 5 votes vote down vote up
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 49
Project: learn_python3_spider   Author: wistbean   File: udp.py    License: MIT License 5 votes vote down vote up
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 50
Project: learn_python3_spider   Author: wistbean   File: udp.py    License: MIT License 5 votes vote down vote up
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 51
Project: learn_python3_spider   Author: wistbean   File: udp.py    License: MIT License 5 votes vote down vote up
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 52
Project: learn_python3_spider   Author: wistbean   File: udp.py    License: MIT License 5 votes vote down vote up
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 53
Project: python-orvibo   Author: happyleavesaoc   File: s20.py    License: MIT License 5 votes vote down vote up
def _setup():
    """ Set up module.

    Open a UDP socket, and listen in a thread.
    """
    _SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    _SOCKET.bind(('', PORT))
    udp = threading.Thread(target=_listen, daemon=True)
    udp.start() 
Example 54
Project: scalyr-agent-2   Author: scalyr   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def enableBroadcast(self, flag=1):
        try:
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_BROADCAST, flag
            )
        except socket.error:
            raise error.CarrierError('setsockopt() for SO_BROADCAST failed: %s' % (sys.exc_info()[1],))
        debug.logger & debug.flagIO and debug.logger('enableBroadcast: %s option SO_BROADCAST on socket %s' % (turnOn and "enabled" or "disabled", self.socket.fileno()))
        return self 
Example 55
Project: addon   Author: alfa-addon   File: NetBIOSProtocol.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, broadcast = True, listen_port = 0):
        """
        Instantiate a NBNSProtocol instance.

        This automatically calls reactor.listenUDP method to start listening for incoming packets, so you **must not** call the listenUDP method again.

        :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode
        :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.
        """
        self.broadcast = broadcast
        self.pending_trns = { }  # TRN ID -> ( expiry_time, name, Deferred instance )
        self.transport = reactor.listenUDP(listen_port, self)
        if self.broadcast:
            self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        reactor.callLater(1, self.cleanupPendingTrns) 
Example 56
Project: addon   Author: alfa-addon   File: NetBIOS.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, broadcast = True, listen_port = 0):
        """
        Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets.

        :param boolean broadcast: A boolean flag to indicate if we should setup the listening UDP port in broadcast mode
        :param integer listen_port: Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.
        """
        self.broadcast = broadcast
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        if self.broadcast:
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        if listen_port:
            self.sock.bind(( '', listen_port )) 
Example 57
Project: TOOLS   Author: DOWRIGHTTV   File: lan_buster.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Main(self):
        self.sock = socket(AF_INET, SOCK_DGRAM)
        self.sock.setsockopt(SOL_SOCKET, SO_REUSEADDR,1)
        self.sock.setsockopt(SOL_SOCKET, SO_BROADCAST,1)
        self.sock.setsockopt(SOL_SOCKET, SO_BINDTODEVICE, self.bind_int)
        self.sock.bind(('0.0.0.0', 68)) 
Example 58
Project: Roomba980-Python   Author: NickWaterton   File: password.py    License: MIT License 5 votes vote down vote up
def receive_udp(self):
        #set up UDP socket to receive data from robot
        port = 5678
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(10)
        if self.address == '255.255.255.255':
            s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.bind(("", port))  #bind all intefaces to port
        print("waiting on port: %d for data" % port)
        message = 'irobotmcs'
        s.sendto(message.encode(), (self.address, port))
        roomba_dict = {}
        while True:
            try:
                udp_data, addr = s.recvfrom(1024)   #wait for udp data
                #print('Received: Robot addr: %s Data: %s ' % (addr, udp_data))
                if len(udp_data) > 0:
                    if udp_data != message:
                        try:
                            if self.address != addr[0]:
                                self.log.warn(
                                    "supplied address %s does not match "
                                    "discovered address %s, using discovered "
                                    "address..." % (self.address, addr[0]))
                            if udp_data.decode() != message:
                                parsedMsg = json.loads(udp_data.decode()) #1.2.3 added .decode() to avoid python 3 bytes error
                                roomba_dict[addr]=parsedMsg
                        except Exception as e:
                            print("json decode error: %s" % e)
                            print('RECEIVED: %s', pformat(udp_data))
                        # print('Robot Data: %s '
                        #       % json.dumps(parsedMsg, indent=2))
                else:
                    break
            except socket.timeout:
                break
        s.close()
        return roomba_dict 
Example 59
Project: Roomba980-Python   Author: NickWaterton   File: password.py    License: MIT License 5 votes vote down vote up
def receive_udp(self):
        #set up UDP socket to receive data from robot
        port = 5678
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(10)
        if self.address == '255.255.255.255':
            s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.bind(("", port))  #bind all intefaces to port
        print("waiting on port: %d for data" % port)
        message = 'irobotmcs'
        s.sendto(message.encode(), (self.address, port))
        roomba_dict = {}
        while True:
            try:
                udp_data, addr = s.recvfrom(1024)   #wait for udp data
                #print('Received: Robot addr: %s Data: %s ' % (addr, udp_data))
                if len(udp_data) > 0:
                    if udp_data != message:
                        try:
                            if self.address != addr[0]:
                                self.log.warn(
                                    "supplied address %s does not match "
                                    "discovered address %s, using discovered "
                                    "address..." % (self.address, addr[0]))
                            if udp_data.decode() != message:
                                parsedMsg = json.loads(udp_data)
                                roomba_dict[addr]=parsedMsg
                        except Exception as e:
                            print("json decode error: %s" % e)
                            print('RECEIVED: %s', pformat(udp_data))
                        # print('Robot Data: %s '
                        #       % json.dumps(parsedMsg, indent=2))
                else:
                    break
            except socket.timeout:
                break
        s.close()
        return roomba_dict 
Example 60
Project: winops   Author: google   File: dhcp.py    License: Apache License 2.0 5 votes vote down vote up
def GetDhcpOption(client_addr,
                  client_mac,
                  option,
                  server_addr='255.255.255.255',
                  socket_timeout=10):
  """Requests a DHCP option (RFC2132) from a DHCP server.

  Args:
    client_addr: The client IP address as a string.
    client_mac: The client MAC address as a string.
    option: The option number being requested by the user.
    server_addr: The DHCP server address to target.
    socket_timeout: How long to wait for a response on port 68.

  Returns:
    The response payload corresponding to the requested option, or None.
  """
  result = None
  option = int(option)
  data = _BuildPacket(client_addr, client_mac, option)

  if not data:
    logging.error('Cannot compile DHCP request.')
    return result

  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  sock.bind((client_addr, 68))
  sock.settimeout(socket_timeout)

  sock.sendto(data, (server_addr, 67))
  response = None
  try:
    response = sock.recv(1024)
  except socket.timeout:
    logging.error('Timed out waiting for response.')
  if response:
    result = _OptScan(response[240:], option)
  return result