Python socket.SO_BROADCAST属性代码示例

本文整理汇总了Python中socket.SO_BROADCAST属性的典型用法代码示例。如果您正苦于以下问题:Python socket.SO_BROADCAST属性的具体用法?Python socket.SO_BROADCAST怎么用?Python socket.SO_BROADCAST使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在模块socket的用法示例。

在下文中一共展示了socket.SO_BROADCAST属性的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:smarthall,项目名称:python-lifx-sdk,代码行数:18,代码来源:network.py


示例2: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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) 
开发者ID:dronekit,项目名称:dronekit-python,代码行数:23,代码来源:mavlink.py


示例3: send_packet

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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) 
开发者ID:juliocesarfort,项目名称:nukemyluks,代码行数:18,代码来源:client.py


示例4: _setup_connection

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:joxeankoret,项目名称:CVE-2017-7494,代码行数:18,代码来源:nmb.py


示例5: test_beacon_already_running

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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() 
开发者ID:tjguk,项目名称:networkzero,代码行数:24,代码来源:test_discovery.py


示例6: wake_on_lan

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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)) 
开发者ID:epoptes,项目名称:epoptes,代码行数:21,代码来源:wol.py


示例7: run

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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)) 
开发者ID:screenfreeze,项目名称:deskcon-desktop,代码行数:24,代码来源:setupdevice.py


示例8: run

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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') 
开发者ID:kanishka-linux,项目名称:kawaii-player,代码行数:23,代码来源:thread_modules.py


示例9: wake_on_lan

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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)) 
开发者ID:jfomu,项目名称:EcoLab,代码行数:20,代码来源:ecolab.py


示例10: discover

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:RussianOtter,项目名称:networking,代码行数:18,代码来源:ap-ro.py


示例11: reboot

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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() 
开发者ID:RussianOtter,项目名称:networking,代码行数:25,代码来源:ap-ro.py


示例12: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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) 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:23,代码来源:DeviceManager.py


示例13: discover

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:krintoxi,项目名称:NoobSec-Toolkit,代码行数:21,代码来源:registry.py


示例14: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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__() 
开发者ID:BasuCert,项目名称:WinboxPoC,代码行数:19,代码来源:MACServerExploit.py


示例15: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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)) 
开发者ID:TUDelft-CNS-ATM,项目名称:bluesky,代码行数:21,代码来源:discovery.py


示例16: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:ralphm2004,项目名称:broadlink-thermostat,代码行数:23,代码来源:__init__.py


示例17: start

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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() 
开发者ID:IDArlingTeam,项目名称:IDArling,代码行数:21,代码来源:discovery.py


示例18: Create

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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
    # ------------------------------------------------------------------------ 
开发者ID:jczic,项目名称:MicroWebSrv2,代码行数:29,代码来源:XAsyncSockets.py


示例19: connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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'))) 
开发者ID:sharph,项目名称:lifx-python,代码行数:31,代码来源:network.py


示例20: addListener

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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) 
开发者ID:alsmith,项目名称:multicast-relay,代码行数:36,代码来源:multicast-relay.py


示例21: main

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:juliocesarfort,项目名称:nukemyluks,代码行数:40,代码来源:server.py


示例22: _server_discovery

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:38,代码来源:connection_manager.py


示例23: _connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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) 
开发者ID:ManiacalLabs,项目名称:BiblioPixel,代码行数:15,代码来源:network_udp.py


示例24: make_output_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:39,代码来源:_ipv4.py


示例25: connection_made

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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()) 
开发者ID:frawau,项目名称:aiotuya,代码行数:9,代码来源:provision.py


示例26: broadlink_hysen_climate_device_setup

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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() 
开发者ID:mairas,项目名称:hysen,代码行数:36,代码来源:climate.py


示例27: run

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
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) 
开发者ID:tjguk,项目名称:networkzero,代码行数:14,代码来源:send_bcast.py


示例28: connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SO_BROADCAST [as 别名]
def connect(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) 
开发者ID:pyvisa,项目名称:pyvisa-py,代码行数:5,代码来源:rpc.py



注:本文中的socket.SO_BROADCAST属性示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。