Python socket 模块,SO_BROADCAST 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.SO_BROADCAST

项目:ironic-staging-drivers    作者:openstack    | 项目源码 | 文件源码
def test_send_magic_packets(self, mock_socket):
        fake_socket = mock.Mock(spec=socket, spec_set=True)
        mock_socket.return_value = fake_socket()
        obj_utils.create_test_port(self.context,
                                   uuid=uuidutils.generate_uuid(),
                                   address='aa:bb:cc:dd:ee:ff',
                                   node_id=self.node.id)
        with task_manager.acquire(
                self.context, self.node.uuid, shared=True) as task:
            wol_power._send_magic_packets(task, '255.255.255.255', 9)

            expected_calls = [
                mock.call(),
                mock.call().setsockopt(socket.SOL_SOCKET,
                                       socket.SO_BROADCAST, 1),
                mock.call().sendto(mock.ANY, ('255.255.255.255', 9)),
                mock.call().sendto(mock.ANY, ('255.255.255.255', 9)),
                mock.call().close()]

            fake_socket.assert_has_calls(expected_calls)
            self.assertEqual(1, mock_socket.call_count)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, port=17935, clients=[], broadcast=True):
        util.Thread.__init__(self)
        self.port = port
        self.clients = clients
        msg = '\x00'.join(["PyritServerAnnouncement",
                        '',
                        str(port)])
        md = hashlib.sha1()
        md.update(msg)
        self.msg = msg + md.digest()
        self.ucast_sckt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        if broadcast:
            self.bcast_sckt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.bcast_sckt.bind(('', 0))
            self.bcast_sckt.setsockopt(socket.SOL_SOCKET, \
                                       socket.SO_BROADCAST, 1)
        else:
            self.bcast_sckt = None
        self.setDaemon(True)
        self.start()
项目:pixelvloed    作者:JanKlopper    | 项目源码 | 文件源码
def __init__(self, queue, options):
    """Init the pixelVloed server"""
    self.debug = options.debug if options.debug else False
    self.pixeloffset = 2
    self.fps = 30
    self.screen = None
    self.udp_ip = options.ip if options.ip else UDP_IP
    self.udp_port = options.port if options.port else UDP_PORT
    self.factor = options.factor if options.factor else 1
    self.canvas()
    self.set_title()
    self.queue = queue
    self.limit = options.maxpixels if options.maxpixels else MAX_PIXELS
    self.pixels = 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)
项目:pixelvloed    作者:JanKlopper    | 项目源码 | 文件源码
def __init__(self, queue, options):
    """Init the pixelVloed server"""
    self.debug = options.debug if options.debug else False
    self.pixeloffset = 2
    self.fps = 30
    self.screen = None
    self.udp_ip = options.ip if options.ip else UDP_IP
    self.udp_port = options.port if options.port else UDP_PORT
    self.factor = options.factor if options.factor else 1
    self.canvas()

    self.queue = queue
    self.limit = options.maxpixels if options.maxpixels else MAX_PIXELS
    self.pixels = 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)
项目:PiBunny    作者:tholum    | 项目源码 | 文件源码
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
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def clientScan(report = None):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.settimeout(30)

        s.bind(('', 8000))

        buf, address = s.recvfrom(64)

        address = address[0]
        port = int(str(buf, encoding='utf8'))

        reporting(report, "Master server found")

        return (address, port)
    except socket.timeout:
        reporting(report, "No master server on network", IOError)

        return ("", 8000) # return default values
项目:BiblioPixel2    作者:ManiacalLabs    | 项目源码 | 文件源码
def _connect(self):
        try:
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            if self._broadcast:
                # self._sock.bind((self._broadcast_interface, self._port))
                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)

    # Push new data to strand
项目:SonyAPI    作者:kdschlosser    | 项目源码 | 文件源码
def _wake_on_lan(self):
        _LOGGER.debug('WOL ' + self.wol_mac)

        address_byte = tuple(
            int(b, 16) for b in self.wol_mac.split(':')
        )
        _LOGGER.debug(address_byte)

        hw_address = struct.pack('BBBBBB', *address_byte)
        msg = b'\xff' * 6 + hw_address * 16
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_BROADCAST,
            1
        )

        sock.sendto(msg, ('<broadcast>', 9))
        sock.close()
        _LOGGER.debug('WOL Packet Sent')
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def __init__(self):
        self.tcpPort = 31337
        self.tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tcpsocket.bind(("0.0.0.0", self.tcpPort))
        self.tcpsocket.listen(10)

        self.discoverysocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

        self.glfwWorkers = {}

        self.controllerConn = None
        self.controllerAddr = None
        self.outbuf = ""    # IO buffer for controller
        self.inbuf = ""

        self.monitors = glfw.get_monitors()

        for monitor in glfw.get_monitors():
            self.glfwWorkers[bytes.decode(glfw.get_monitor_name(monitor))] = glfwWorker(monitor)
项目:python-broadlink    作者:mjg59    | 项目源码 | 文件源码
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
项目:networkzero    作者:tjguk    | 项目源码 | 文件源码
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()
项目:caproto    作者:NSLS-II    | 项目源码 | 文件源码
def bcast_socket(socket_module=socket):
    """
    Make a socket and configure it for UDP broadcast.

    Parameters
    ----------
    socket_module: module, optional
        Default is the built-in :mod:`socket` module, but anything with the
        same interface may be used, such as :mod:`curio.socket`.
    """
    socket = socket_module
    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)

    # for BSD/Darwin only
    try:
        socket.SO_REUSEPORT
    except AttributeError:
        ...
    else:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    return sock
项目:kawaii-player    作者:kanishka-linux    | 项目源码 | 文件源码
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={} msg={}'.format(
            port, ui.https_media_server, 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')
项目:WMIControl    作者:crutchcorn    | 项目源码 | 文件源码
def sendWoL(mac, broadcast=findBroadcast()):
    """Given string mac and broadcast: Turn on computer using WoL
    This was taken from http://code.activestate.com/recipes/358449-wake-on-lan/. Thanks, Fadly!
    """
    # Cleans and removes delimiters from MAC
    try:
        mac = format_mac(EUI(mac), mac_bare)
    except AddrFormatError:
        raise ValueError('Incorrect MAC address format')

    # Pad the synchronization stream.
    data = ''.join(['FFFFFFFFFFFF', mac * 20])
    send_data = b''

    # Split up the hex values and pack.
    for i in range(0, len(data), 2):
        send_data = b''.join([send_data, pack('B', int(data[i: i + 2], 16))])

    # Broadcast it to the LAN.
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(send_data, (broadcast, 7))
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def __init__(self, host, port, target_port):

      """
      The constructor ...
      :param host:
      :param port:
      :param target_port:
      """

      super(UDPThreadBroadcastClient, self).__init__()
      self.host = host
      self.port = port
      self.targetPort = target_port
      self.data = None
      self.sentBytes = None
      self.sentBytesLock = threading.Lock()

      self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
      self.sock.bind((host, port))

    # -----------------------------------------------------------------
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def __init__(self, host, port, target_port):

      """
      The constructor ...
      :param host:
      :param port:
      :param target_port:
      """

      super(UDPThreadBroadcastClient, self).__init__()
      self.host = host
      self.port = port
      self.targetPort = target_port
      self.data = None
      self.sentBytes = None
      self.sentBytesLock = threading.Lock()

      self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
      self.sock.bind((host, port))

    # -----------------------------------------------------------------
项目:CVE-2017-7494    作者:joxeankoret    | 项目源码 | 文件源码
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
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, port=17935, clients=[], broadcast=True):
        util.Thread.__init__(self)
        self.port = port
        self.clients = clients
        msg = '\x00'.join(["PyritServerAnnouncement",
                        '',
                        str(port)])
        md = hashlib.sha1()
        md.update(msg)
        self.msg = msg + md.digest()
        self.ucast_sckt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        if broadcast:
            self.bcast_sckt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.bcast_sckt.bind(('', 0))
            self.bcast_sckt.setsockopt(socket.SOL_SOCKET, \
                                       socket.SO_BROADCAST, 1)
        else:
            self.bcast_sckt = None
        self.setDaemon(True)
        self.start()
项目:EcoLab    作者:basfom    | 项目源码 | 文件源码
def wakeOnLan(macaddress):
    if len(macaddress) == 12:
        pass
    elif len(macaddress) == 12 + 5:
        sep = macaddress[2]
        macaddress = macaddress.replace(sep, '')
    else:
        raise ValueError('Formato de MAC incorrecto!') #(EN) Incorrect MAC format!

    data = ''.join(['FFFFFFFFFFFF', macaddress * 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))])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(send_data, ('<broadcast>', 7))

## SEND CMD
项目:ngas    作者:ICRAR    | 项目源码 | 文件源码
def WakeOnLan(ethernet_address):

  # Construct a six-byte hardware address

  addr_byte = ethernet_address.split(':')
  hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16),
    int(addr_byte[1], 16),
    int(addr_byte[2], 16),
    int(addr_byte[3], 16),
    int(addr_byte[4], 16),
    int(addr_byte[5], 16))

  # Build the Wake-On-LAN "Magic Packet"...

  msg = '\xff' * 6 + hw_addr * 16

  # ...and send it to the broadcast address using UDP

  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  s.sendto(msg, ('<broadcast>', 9))
  s.close()
项目:python_light_detector    作者:bkosciow    | 项目源码 | 文件源码
def get_current_state():
    address = ('192.168.1.255', PORT)
    packet = {
        "protocol": "iot:1",
        "node": "computer",
        "event": "state",
        "targets": [
            NODE
        ]
    }

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    msg = json.dumps(packet)
    s.sendto(msg.encode(), address)
    (data, ip) = s.recvfrom(1024)
    state = "unknown"
    try:
        msg = json.loads(data.decode())
        if msg['protocol'] == "iot:1":
            state = msg['response']
    except ValueError:
        pass

    return state
项目:domoticz    作者:ericstaal    | 项目源码 | 文件源码
def sendWOL(self):
    # only if WOL exists
    if not (self.mac is None):
      self.LogMessage("Send WOL to MAC: "+ self.mac, 3)
      data = b'FFFFFFFFFFFF' + (self.mac * 20).encode()
      send_data = b'' 

      # Split up the hex values and pack.
      for i in range(0, len(data), 2):
        send_data += struct.pack('B', int(data[i: i + 2], 16))

      # Broadcast it to the LAN.
      sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
      sock.sendto(send_data, ('255.255.255.255', self.wolport))

####################### Generic helper member functions for plugin #######################
项目:blender-addons    作者:scorpion81    | 项目源码 | 文件源码
def clientScan(report = None):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.settimeout(30)

        s.bind(('', 8000))

        buf, address = s.recvfrom(64)

        address = address[0]
        port = int(str(buf, encoding='utf8'))

        reporting(report, "Master server found")

        return (address, port)
    except socket.timeout:
        reporting(report, "No master server on network", IOError)

        return ("", 8000) # return default values
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def _setup_connection(self, dstaddr):
        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

    # Set the default NetBIOS domain nameserver.
项目:Hardware-Bruteforce-Framework-2    作者:cervoise    | 项目源码 | 文件源码
def WOL(macaddress):
    """ Switches on remote computers using WOL. """

    # Check macaddress format and try to compensate.
    if len(macaddress) == 12:
        pass
    elif len(macaddress) == 12 + 5:
        sep = macaddress[2]
        macaddress = macaddress.replace(sep, '')
    else:
        raise ValueError('Incorrect MAC address format')

    # Pad the synchronization stream.
    data = ''.join(['FFFFFFFFFFFF', macaddress * 20])
    send_data = '' 

    # Split up the hex values and pack.
    for i in range(0, len(data), 2):
        send_data = ''.join([send_data,
                             struct.pack('B', int(data[i: i + 2], 16))])

    # Broadcast it to the LAN.
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(send_data, ('<broadcast>', 7))
项目:decentralized-chat    作者:Phil9l    | 项目源码 | 文件源码
def __init__(self, port=8888, render_message=None, get_nickname=None):
        self.render_message = render_message
        self.get_nickname = get_nickname
        self.nickname = self.get_nickname()
        self.port = port
        # connecting to server
        try:
            self.sock_to_read = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock_to_read.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock_to_read.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            self.sock_to_read.bind(('0.0.0.0', port))

            self.sock_to_write = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock_to_write.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        except Exception as e:
            raise ConnectionError('Unable to connect')
项目:bravialib    作者:8none1    | 项目源码 | 文件源码
def wakeonlan(self, mac=None):
        # Thanks: Taken from https://github.com/aparraga/braviarc/blob/master/braviarc/braviarc.py
        # Not using another library for this as it's pretty small...
        if mac is None and self.mac_addr is not None:
            mac = self.mac_addr
        print "Waking MAC: " + mac
        addr_byte = mac.split(':')
        hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16),
                              int(addr_byte[1], 16),
                              int(addr_byte[2], 16),
                              int(addr_byte[3], 16),
                              int(addr_byte[4], 16),
                              int(addr_byte[5], 16))
        msg = b'\xff' * 6 + hw_addr * 16
        socket_instance = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        socket_instance.sendto(msg, ('<broadcast>', 9))
        socket_instance.close()
        return True
项目:networking    作者:RussianOtter    | 项目源码 | 文件源码
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
项目:networking    作者:RussianOtter    | 项目源码 | 文件源码
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()
项目:maas    作者:maas    | 项目源码 | 文件源码
def send_dhcp_request_packet(
        request: DHCPDiscoverPacket, ifname: str) -> None:
    """Sends out the specified DHCP discover packet to the given interface.

    Optionally takes a `retry_call` to cancel if a fatal error occurs before
    the first packet can be sent, such as inability to get a source IP
    address.
    """
    with udp_socket() as sock:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        mac = get_interface_mac(sock, ifname)
        request.set_mac(mac)
        bind_address = get_interface_ip(sock, ifname)
        sock.bind((bind_address, BOOTP_CLIENT_PORT))
        sock.sendto(request.packet, ('<broadcast>', BOOTP_SERVER_PORT))


# Packets will be sent at the following intervals (in seconds).
# The length of `DHCP_REQUEST_TIMING` indicates the number of packets
# that will be sent. The values should get progressively larger, to mimic
# the exponential back-off retry behavior of a real DHCP client.
项目:HoneySMB    作者:r0hi7    | 项目源码 | 文件源码
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
项目:pyserver    作者:juhgiyo    | 项目源码 | 文件源码
def __init__(self, port, callback, bindaddress=''):
        asyncore.dispatcher.__init__(self)
        # self.lock = threading.RLock()
        self.MAX_MTU = 1500
        self.callback = None
        self.port = port
        if callback is not None and isinstance(callback, IUdpCallback):
            self.callback = callback
        else:
            raise Exception('callback is None or not an instance of IUdpCallback class')
        try:
            self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            # self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.set_reuse_addr()
            self.bind((bindaddress, port))
        except Exception as e:
            print e
            traceback.print_exc()
        self.send_queue = Queue.Queue()  # thread-safe queue
        AsyncController.instance().add(self)
        if self.callback is not None:
            self.callback.on_started(self)

    # Even though UDP is connectionless this is called when it binds to a port
项目:Automation-Framework-for-devices    作者:tok-gogogo    | 项目源码 | 文件源码
def __init__(self,HOST=None,PORT='9999',DEBUG_FLAG=True):
        #-----------------------------------------------------------------------------
        # Name:        init fuction
        # param:       HOST:host name PORT:PORT 
        # explain:     initialize the myudp class
        # Author:      gongke
        #
        # Created:     2013/01/15
        #-----------------------------------------------------------------------------
        self.host = HOST
        self.port = string.atoi(PORT)
        if string.atoi(DEBUG_FLAG)==1:
            self.debugflag = True
        else:
            self.debugflag = False
        #self.debugflag = DEBUG_FLAG
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.settimeout(20)
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def discover_peers(self, port=None):
        """This method can be invoked (periodically?) to broadcast message to
        discover peers, if there is a chance initial broadcast message may be
        lost (as these messages are sent over UDP).
        """
        ping_msg = {'signature': self._signature, 'name': self._name, 'version': __version__}

        def _discover(addrinfo, port, task=None):
            ping_sock = AsyncSocket(socket.socket(addrinfo.family, socket.SOCK_DGRAM))
            ping_sock.settimeout(2)
            if addrinfo.family == socket.AF_INET:
                ping_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            else:  # addrinfo.family == socket.AF_INET6
                ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS,
                                     struct.pack('@i', 1))
                ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, addrinfo.ifn)
            ping_sock.bind((addrinfo.ip, 0))
            if not port:
                port = addrinfo.udp_sock.getsockname()[1]
            ping_msg['location'] = addrinfo.location
            try:
                yield ping_sock.sendto('ping:'.encode() + serialize(ping_msg),
                                       (addrinfo.broadcast, port))
            except:
                pass
            ping_sock.close()

        for addrinfo in self._addrinfos:
            SysTask(_discover, addrinfo, port)
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def discover_peers(self, port=None):
        """This method can be invoked (periodically?) to broadcast message to
        discover peers, if there is a chance initial broadcast message may be
        lost (as these messages are sent over UDP).
        """
        ping_msg = {'signature': self._signature, 'name': self._name, 'version': __version__}

        def _discover(addrinfo, port, task=None):
            ping_sock = AsyncSocket(socket.socket(addrinfo.family, socket.SOCK_DGRAM))
            ping_sock.settimeout(2)
            if addrinfo.family == socket.AF_INET:
                ping_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            else:  # addrinfo.family == socket.AF_INET6
                ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS,
                                     struct.pack('@i', 1))
                ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, addrinfo.ifn)
            ping_sock.bind((addrinfo.ip, 0))
            if not port:
                port = addrinfo.udp_sock.getsockname()[1]
            ping_msg['location'] = addrinfo.location
            try:
                yield ping_sock.sendto('ping:'.encode() + serialize(ping_msg),
                                       (addrinfo.broadcast, port))
            except:
                pass
            ping_sock.close()

        for addrinfo in self._addrinfos:
            SysTask(_discover, addrinfo, port)
项目:ironic-staging-drivers    作者:openstack    | 项目源码 | 文件源码
def _send_magic_packets(task, dest_host, dest_port):
    """Create and send magic packets.

    Creates and sends a magic packet for each MAC address registered in
    the Node.

    :param task: a TaskManager instance containing the node to act on.
    :param dest_host: The broadcast to this IP address.
    :param dest_port: The destination port.
    :raises: WOLOperationError if an error occur when connecting to the
        host or sending the magic packets

    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    with contextlib.closing(s) as sock:
        for port in task.ports:
            address = port.address.replace(':', '')

            # TODO(lucasagomes): Implement sending the magic packets with
            # SecureON password feature. If your NIC is capable of, you can
            # set the password of your SecureON using the ethtool utility.
            data = 'FFFFFFFFFFFF' + (address * 16)
            packet = bytearray.fromhex(data)

            try:
                sock.sendto(packet, (dest_host, dest_port))
            except socket.error as e:
                msg = (_("Failed to send Wake-On-Lan magic packets to "
                         "node %(node)s port %(port)s. Error: %(error)s") %
                       {'node': task.node.uuid, 'port': port.address,
                        'error': e})
                LOG.exception(msg)
                raise exception.WOLOperationError(msg)

            # let's not flood the network with broadcast packets
            time.sleep(0.5)
项目:hmv-s16    作者:cmuphyscomp    | 项目源码 | 文件源码
def mkcmdsock(ip_address=None, port=0):
    "Create a command socket."
    ip_address = gethostip() if not ip_address else ip_address
    cmdsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    cmdsock.bind((ip_address, port))
    cmdsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    cmdsock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFSIZE)
    return cmdsock
项目:hmv-s16    作者:cmuphyscomp    | 项目源码 | 文件源码
def make_data_sender_socket(ip_address=None):
    """Create a socket for sending multicast data."""
    ip_address = gethostip() if not ip_address else ip_address
    datasock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20)

    # print("Binding source socket to %s" % ip_address)
    datasock.bind((ip_address, 0))
    return datasock
项目:n1mm_view    作者:n1kdo    | 项目源码 | 文件源码
def listener(db, cursor):
    """
    this is the UDP listener, the main loop.
    """
    s = socket(AF_INET, SOCK_DGRAM)
    s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    try:
        s.bind(('', config.N1MM_BROADCAST_PORT))
    except:
        logging.critical('Error connecting to the UDP stream.')
        return

    operators = Operators(db, cursor)
    stations = Stations(db, cursor)

    seen = set()
    run = True
    while run:
        try:
            udp_data = s.recv(BROADCAST_BUF_SIZE)
            process_message(db, cursor, operators, stations, udp_data, seen)

        except KeyboardInterrupt:
            logging.info('Keyboard interrupt, shutting down...')
            s.close()
            run = False
项目:solar    作者:mhvis    | 项目源码 | 文件源码
def __init__(self, interface_ip=''):
        # Start server to listen for incoming connections
        listen_port = 1200
        logger.debug('Binding TCP socket to %s:%s', interface_ip, listen_port)
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.bind((interface_ip, listen_port))
        self.server.settimeout(5.0) # Timeout defines time between broadcasts
        self.server.listen(5)
        # Creating and binding broadcast socket
        logger.debug('Binding UDP socket to %s:%s', interface_ip, 0)
        self.bc_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.bc_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.bc_sock.bind((interface_ip, 0))
项目:PyCIP    作者:cpchrispye    | 项目源码 | 文件源码
def list_identity(target_ip='255.255.255.255', target_port=44818, udp=True):
        sockets = []
        responses = []
        delay = 1000
        header = ENIPEncapsulationHeader(ENIPCommandCode.ListIdentity, 0, 0, 0, delay, 0)
        data = header.export_data()
        networks = networking.list_networks()

        for ifc in networks:
            if udp:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.bind((ifc, 0))
                s.setblocking(0)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            else:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.sendto(data, (target_ip, target_port))
            sockets.append(s)
        time.sleep(1.1*delay/1000)
        packets = []
        for s in sockets:
            try:
                while True:
                    packets.append(s.recv(65535))
            except BlockingIOError:
                pass

        for packet in packets:
            if len(packet) < 42:
                continue
            rsp_header = ENIPEncapsulationHeader()
            offset = rsp_header.import_data(packet)
            li = ListIdentityRsp()
            offset += li.import_data(packet, offset)
            responses.append(li)
        return responses

    # this ideally will use asyncio to manage connections
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self):
        util.Thread.__init__(self)
        self.cv = threading.Condition()
        self.servers = []
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.bind(('', 17935))
        self.setDaemon(True)
        self.start()
项目:pyNet    作者:mcvavy    | 项目源码 | 文件源码
def __init__(self, thisNode):
        logging.info('Initializing listener')
        self.thisNode = thisNode
        self.MCAST_PORT = 4242
        self.MCAST_GRP = '192.168.1.255'

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.bind(('', self.MCAST_PORT))
项目:reinforcement_learning    作者:andreweskeclarke    | 项目源码 | 文件源码
def main():
    self.broadcast_port = 8080
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    self.sock.bind(('', 0))

    index = 1
    while True:
        self.sock.sendto('...' + index, ("<broadcast>", self.broadcast_port))
        index += 1
        sys.stdout.flush()
项目:reinforcement_learning    作者:andreweskeclarke    | 项目源码 | 文件源码
def __init__(self, broadcast_port=BROADCAST_PORT):
        self.broadcast_port = int(os.environ.get('BROADCAST_PORT', BROADCAST_PORT))
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.bind(('', 0))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def runMaster(address, broadcast, clear, force, path, update_stats, test_break,use_ssl=False,cert_path="",key_path=""):
    httpd = createMaster(address, clear, force, path)
    httpd.timeout = 1
    httpd.stats = update_stats
    if use_ssl:
        import ssl
        httpd.socket = ssl.wrap_socket(
                httpd.socket,
                certfile=cert_path,
                server_side=True,
                keyfile=key_path,
                ciphers="ALL",
                ssl_version=ssl.PROTOCOL_SSLv23,
                )
    if broadcast:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    start_time = time.time() - 2

    while not test_break():
        try:
            httpd.handle_request()
        except select.error:
            pass

        if time.time() - start_time >= 2: # need constant here
            httpd.timeoutSlaves()

            httpd.updateUsage()

            if broadcast:
                print("broadcasting address")
                s.sendto(bytes("%i" % address[1], encoding='utf8'), 0, ('<broadcast>', 8000))
                start_time = time.time()

    httpd.server_close()
    if clear:
        clearMaster(httpd.path)
    else:
        saveMaster(path, httpd)
项目:BiblioPixel2    作者:ManiacalLabs    | 项目源码 | 文件源码
def _generateHeader(self, cmd, size):
        packet = bytearray()
        packet.append(cmd)
        packet.append(size & 0xFF)
        packet.append(size >> 8)
        return packet

# s = socket(AF_INET, SOCK_DGRAM)
# s.bind(('', 0))
# s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
项目:ControlCentre    作者:cctry    | 项目源码 | 文件源码
def register(ssid, key):
    """
    the entrance function of SmartConfig(tmd)
    :type ssid: str
    :type key: str
    """
    port = 8514
    data = {'key':encode(key), 'ssid':encode(ssid)}
    s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    for i in xrange(10):
        send(s, port, data, ssid, key)
        sleep(100)
项目:python-broadlink    作者:mjg59    | 项目源码 | 文件源码
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))
项目:Roomba980-Python    作者:NickWaterton    | 项目源码 | 文件源码
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