Python socket.SOL_SOCKET属性代码示例

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

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

示例1: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [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 SOL_SOCKET [as 别名]
def __init__(self, eventHandler):
        threading.Thread.__init__(self)
        self.name = 'Server'
        self.daemon = True
        self._eventHandler = eventHandler
        self._client = None
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            self._server.bind(('', PORT))
            self._server.listen(5)
        except socket.error:
            event = Event(Events.SCAN_ERROR, msg='Could not start server')
            post_event(eventHandler, event)
            return
        self._cancel = False
        self.start() 
开发者ID:EarToEarOak,项目名称:RF-Monitor,代码行数:22,代码来源:server.py


示例3: serve

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def serve(self):
		server_socket = None
		try:
			common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			whereto = (self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport")))
			server_socket.bind(whereto)
			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False
			self.communication_initialization()
			self.communication(False)
			
		except KeyboardInterrupt:
			self.cleanup()
			return
		self.cleanup()
		return 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:26,代码来源:UDP_generic.py


示例4: acceptThread

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def acceptThread(parameters):
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(parameters['listenPort'])))
    acceptor.listen(5)
    cur_thread = threading.current_thread()
    logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')
    while True:
        (clientSock, clientAddr) = acceptor.accept()
        print "==== Output Request ====="
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        logger.info(msg)
        thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
        thread3.daemon = True
        thread3.start()
    acceptor.close()
    return 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:20,代码来源:script_runner.py


示例5: acceptThread

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def acceptThread():
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(uploadPort)))
    acceptor.listen(5)
    cur_thread=threading.current_thread()
    while True:
        (clientSock,clientAddr)=acceptor.accept()
        print "====Output Request:"
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        print msg
        thread3=threading.Thread(target=sendFile(clientSock))
        thread3.daemon=True
        thread3.start()
        #thread3.join()
    acceptor.close()
    return 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:20,代码来源:reporting_send.py


示例6: Create

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def Create(asyncSocketsPool, srvAddr, srvBacklog=256, bufSlots=None) :
        try :
            srvSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except :
            raise XAsyncTCPServerException('Create : Cannot open socket (no enought memory).')
        try :
            srvSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            srvSocket.bind(srvAddr)
            srvSocket.listen(srvBacklog)
        except :
            raise XAsyncTCPServerException('Create : Error to binding the TCP server on this address.')
        if not bufSlots :
            bufSlots = XBufferSlots(256, 4096, keepAlloc=True)
        xAsyncTCPServer = XAsyncTCPServer( asyncSocketsPool,
                                           srvSocket,
                                           srvAddr,
                                           bufSlots )
        asyncSocketsPool.NotifyNextReadyForReading(xAsyncTCPServer, True)
        return xAsyncTCPServer
    # ------------------------------------------------------------------------ 
开发者ID:jczic,项目名称:MicroWebSrv2,代码行数:23,代码来源:XAsyncSockets.py


示例7: start_server

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def start_server(port):
    # Start the server
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('', port))
    server_socket.listen(128)  # Maximum connections Mac OSX can handle.
    status_messages.append(MESSAGE_INFO + "Successfully started the server on port {0}.".format(str(port)))
    status_messages.append(MESSAGE_INFO + "Waiting for clients...")
    while True:
        client_connection, client_address = ssl.wrap_socket(server_socket, cert_reqs=ssl.CERT_NONE, server_side=True, keyfile="server.key", certfile="server.crt").accept()
        status_messages.append(MESSAGE_INFO + "New client connected!")
        connections.append(client_connection) 
开发者ID:cys3c,项目名称:EvilOSX,代码行数:18,代码来源:Server.py


示例8: bind_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
    """Create TCP server socket.
    :param host: IPv4, IPv6 or hostname may be specified
    :param port: TCP port number
    :param backlog: Maximum number of connections to queue
    :return: socket.socket object
    """
    try:  # IP address: family must be specified for IPv6 at least
        ip = ip_address(host)
        host = str(ip)
        sock = socket.socket(
            socket.AF_INET6 if ip.version == 6 else socket.AF_INET
        )
    except ValueError:  # Hostname, may become AF_INET or AF_INET6
        sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(backlog)
    return sock 
开发者ID:huge-success,项目名称:sanic,代码行数:21,代码来源:server.py


示例9: make_socket_proxy

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def make_socket_proxy(ip, port, send_callback=None, recv_callback=None):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('', 8080))
    server.listen(1)
    t = threading.Thread(
        target=listen,
        args=(server, ip, port, send_callback, recv_callback)
    )
    t.start()
    sock = socket.create_connection(('localhost', 8080))
    sock.settimeout(1)
    t.join()
    with _socket_lock:
        data = _sockets[t.ident]
        return (sock, data['lsock'], data['rsock'], server) 
开发者ID:wbond,项目名称:oscrypto,代码行数:18,代码来源:_socket_proxy.py


示例10: connection_made

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def connection_made(self, transport):
        self.transport = transport
        self.log.debug('SerialConnection: port opened: {}'.format(transport))
        if self.is_net:
            # we don't want to buffer the entire file on the host
            transport.get_extra_info('socket').setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
            self.log.info("SerialConnection: Setting net tx buf to 2048")
            # for net we want to limit how much we queue up otherwise the whole file gets queued
            # this also gives us more progress more often
            transport.set_write_buffer_limits(high=1024, low=256)
            self.log.info('SerialConnection: Buffer limits: {} - {}'.format(transport._high_water, transport._low_water))
        else:
            transport.set_write_buffer_limits(high=1024, low=64)
            self.log.info('SerialConnection: Buffer limits: {} - {}'.format(transport._high_water, transport._low_water))
            # transport.serial.rts = False  # You can manipulate Serial object via transport
            transport.serial.reset_input_buffer()
            transport.serial.reset_output_buffer()
            # transport.serial.set_low_latency_mode(True)
            # print(transport.serial) 
开发者ID:wolfmanjm,项目名称:kivy-smoothie-host,代码行数:21,代码来源:comms.py


示例11: peer_creds

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def peer_creds(self):
        if self._creds is not False:
            return self._creds
        # works only for unix sockets
        if self.request.family != socket.AF_UNIX:
            self._creds = None
            return self._creds
        # pid_t: signed int32, uid_t/gid_t: unsigned int32
        fmt = 'iII'
        creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERCRED,
                                        struct.calcsize(fmt))
        pid, uid, gid = struct.unpack(fmt, creds)
        try:
            creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERSEC,
                                            SELINUX_CONTEXT_LEN)
            context = creds.rstrip(b'\x00').decode('utf-8')
        except Exception:  # pylint: disable=broad-except
            logger.debug("Couldn't retrieve SELinux Context", exc_info=True)
            context = None
        self._creds = {'pid': pid, 'uid': uid, 'gid': gid, 'context': context}
        return self._creds 
开发者ID:latchset,项目名称:custodia,代码行数:24,代码来源:server.py


示例12: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [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


示例13: test_timeout_empty

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def test_timeout_empty():
    # Create a dummy server.
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('127.0.0.1', 5760))
    s.listen(1)
    try:
        # Connect with timeout of 10s.
        vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True, heartbeat_timeout=20)
        vehicle.close()
        # Should not pass
        assert False
    except:
        pass 
开发者ID:dronekit,项目名称:dronekit-python,代码行数:19,代码来源:test_timeout.py


示例14: _create_ipv4_sockets

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def _create_ipv4_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    mcast_address = "224.0.1.195"
    port = 49501
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=4sl", socket.inet_aton(mcast_address), socket.INADDR_ANY)
    rxsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
    rxsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    rxsock.bind(group)
    return (txsock, rxsock) 
开发者ID:brunorijsman,项目名称:rift-python,代码行数:21,代码来源:multicast_checks.py


示例15: _create_ipv6_sockets

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def _create_ipv6_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    intf_name = find_ethernet_interface()
    intf_index = socket.if_nametoindex(intf_name)
    mcast_address = "ff02::abcd:99"
    port = 30000
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, intf_index)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=16si", socket.inet_pton(socket.AF_INET6, mcast_address), intf_index)
    if platform.system() == "Darwin":
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, req)
    else:
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_ADD_MEMBERSHIP, req)
    rxsock.bind(("::", port))
    return (txsock, rxsock) 
开发者ID:brunorijsman,项目名称:rift-python,代码行数:26,代码来源:multicast_checks.py


示例16: _handle_connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:iostream.py


示例17: send_packet

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [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


示例18: reserve_sock_addr

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def reserve_sock_addr() -> Iterator[Tuple[str, int]]:
    """Reserve an available TCP port to listen on.
    The reservation is done by binding a TCP socket to port 0 with
    ``SO_REUSEPORT`` flag set (requires Linux >=3.9). The socket is
    then kept open until the generator is closed.
    To reduce probability of 'hijacking' port, socket should stay open
    and should be closed _just before_ starting of ``tf.train.Server``
    """
    so_reuseport = get_so_reuseport()
    if so_reuseport is None:
        raise RuntimeError(
            "SO_REUSEPORT is not supported by the operating system") from None
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.setsockopt(socket.SOL_SOCKET, so_reuseport, 1)
        sock.bind(("", 0))
        _ipaddr, port = sock.getsockname()
        yield (socket.getfqdn(), port) 
开发者ID:criteo,项目名称:tf-yarn,代码行数:22,代码来源:_internal.py


示例19: bind_unused_port

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def bind_unused_port(sock: socket.socket, host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = 'localhost') -> int:
    """Bind the socket to a free port and return the port number.
    This code is based on the code in the stdlib's test.test_support module."""
    if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
            with contextlib.suppress(socket.error):
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
    if not isinstance(host, str):
        host = str(host)
    if sock.family == socket.AF_INET:
        if host == 'localhost':
            sock.bind(('127.0.0.1', 0))
        else:
            sock.bind((host, 0))
    elif sock.family == socket.AF_INET6:
        if host == 'localhost':
            sock.bind(('::1', 0, 0, 0))
        else:
            sock.bind((host, 0, 0, 0))
    else:
        raise CommunicationError("unsupported socket family: " + str(sock.family))
    return sock.getsockname()[1] 
开发者ID:irmen,项目名称:Pyro5,代码行数:24,代码来源:socketutil.py


示例20: build_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def build_socket(self):
        """
        Generate either an HTTPS or HTTP socket
        """
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(self.SOCKET_TIMEOUT)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # Check if TLS
            if self.request_object.protocol == 'https':
                self.sock = ssl.wrap_socket(self.sock, ciphers=self.CIPHERS)
            self.sock.connect(
                (self.request_object.dest_addr, self.request_object.port))
        except socket.error as msg:
            raise errors.TestError(
                'Failed to connect to server',
                {
                    'host': self.request_object.dest_addr,
                    'port': self.request_object.port,
                    'proto': self.request_object.protocol,
                    'message': msg,
                    'function': 'http.HttpUA.build_socket'
                }) 
开发者ID:fastly,项目名称:ftw,代码行数:25,代码来源:http.py


示例21: serve

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def serve(self):
		client_socket = server_socket = None
		self.threads = []
		threadsnum = 0
		common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
		server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			server_socket.bind((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
			while not self._stop:
				server_socket.listen(1) #?? 1 ??
				client_socket, client_addr = server_socket.accept()
				common.internal_print(("Client connected: {0}".format(client_addr)), 0, self.verbosity, common.DEBUG)
				threadsnum = threadsnum + 1
				thread = TCP_generic_thread(threadsnum, 1, self.tunnel, self.packetselector, client_socket, client_addr, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
				thread.start()
				self.threads.append(thread)
			if self._stop:
				self.stop()
		except socket.error as exception:
			# [Errno 98] Address already in use
			if ((self.os_type == common.OS_LINUX) and (exception.args[0] == 98)) or ((self.os_type == common.OS_MACOSX) and (exception.args[0] == 48)):
				common.internal_print("Starting failed, port is in use: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))), -1)
			else:
				raise
		self.cleanup(server_socket)
		return 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:35,代码来源:TCP_generic.py


示例22: serve

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def serve(self):
		server_socket = None
		if self.zonefile:
			(hostname, self.ttl, self.zone) = self.DNS_common.parse_zone_file(self.zonefile)
			if hostname and (hostname+"." != self.hostname):
				common.internal_print("'hostname' in '{0}' section does not match with the zonefile's origin".format(self.get_module_configname()), -1)
				return
		try:
			common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), self.serverport))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			whereto = (self.config.get("Global", "serverbind"), self.serverport)
			server_socket.bind(whereto)
			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False
			self.communication_initialization()
			self.communication(False)
			
		except KeyboardInterrupt:
			self.cleanup()
			return
		self.cleanup()
		return 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:31,代码来源:DNS.py


示例23: serve

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def serve(self):
		client_socket = server_socket = None
		self.threads = []
		threadsnum = 0
		common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
		server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			server_socket.bind((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
			while not self._stop:
				server_socket.listen(1) #?? 1 ??
				client_socket, client_addr = server_socket.accept()
				common.internal_print(("Client connected: {0}".format(client_addr)), 0, self.verbosity, common.DEBUG)
				threadsnum = threadsnum + 1
				thread = SCTP_generic_thread(threadsnum, 1, self.tunnel, self.packetselector, client_socket, client_addr, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
				thread.start()
				self.threads.append(thread)
			if self._stop:
				self.stop()
		except socket.error as exception:
			# [Errno 98] Address already in use
			if exception.args[0] != 98:
				raise
			else:
				common.internal_print("Starting failed, port is in use: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))), -1)
		self.cleanup(server_socket)
		return 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:35,代码来源:SCTP_generic.py


示例24: serve

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def serve(self):
		client_socket = server_socket = None
		self.threads = []
		threadsnum = 0
		common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
		server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			server_socket.bind((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
			while not self._stop:
				server_socket.listen(1) #?? 1 ??
				client_socket, client_addr = server_socket.accept()
				common.internal_print(("Client connected: {0}".format(client_addr)), 0, self.verbosity, common.DEBUG)
				threadsnum = threadsnum + 1
				thread = WebSocket_thread(threadsnum, 1, self.tunnel, self.packetselector, client_socket, client_addr, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
				thread.start()
				self.threads.append(thread)
		except socket.error as exception:
			# [Errno 98] Address already in use
			if exception.args[0] != 98:
				raise
			else:
				common.internal_print("Starting failed, port is in use: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))), -1)
		self.cleanup(server_socket)
		return 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:34,代码来源:WebSocket.py


示例25: init

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def init(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.socket.connect((self.ms_ip, self.ms_tcp_port))
        self.socket_1 = socket.socket()
        self.recv_handle_live = True
        self.recv_thread = threading.Thread(target=self.recv_handler)
        self.recv_thread.daemon = True
        self.session = Session()
        self.session.conf = {}
        self.session.locks = {}
        self.last_send = 0 
开发者ID:rnbguy,项目名称:pysphere,代码行数:15,代码来源:misphere.py


示例26: perform_ssdp_discovery

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def perform_ssdp_discovery(service, timeout=5, retries=5, mx=3):
    # Standard multicast IP address and port for SSDP.
    group = ("239.255.255.250", 1900)
    message = "\r\n".join([
        "M-SEARCH * HTTP/1.1",
        "HOST: {0}:{1}",
        'MAN: "ssdp:discover"',
        "ST: {st}",
        "MX: {mx}"
    ]).format(*group, st=service, mx=mx)
    socket.setdefaulttimeout(timeout)
    sources = set()
    for _ in range(retries):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        sock.sendto(message.encode('utf-8'), group)
        while True:
            try:
                data, addr = sock.recvfrom(1024)
                response = SsdpResponse(data, addr)
                if addr[0] not in sources:
                    # We only want to return each node once.
                    sources.add(addr[0])
                    yield response
            except socket.timeout:
                break 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:32,代码来源:discover.py


示例27: OnReadyForWriting

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def OnReadyForWriting(self) :
        if not self._socketOpened :
            if hasattr(self._socket, "getsockopt") :
                if self._socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) :
                    self._close(XClosedReason.Error, triggerOnClosed=False)
                    if self._onFailsToConnect :
                        try :
                            self._onFailsToConnect(self)
                        except Exception as ex :
                            raise XAsyncTCPClientException('Error when handling the "OnFailsToConnect" event : %s' % ex)
                    return
                self._cliAddr = self._socket.getsockname()
                self._removeExpireTimeout()
            self._socketOpened = True
            if self._onConnected :
                try :
                    self._onConnected(self)
                except Exception as ex :
                    raise XAsyncTCPClientException('Error when handling the "OnConnected" event : %s' % ex)
        if self._wrBufView :
            try :
                n = self._socket.send(self._wrBufView)
            except :
                return
            self._wrBufView = self._wrBufView[n:]
            if not self._wrBufView :
                self._asyncSocketsPool.NotifyNextReadyForWriting(self, False)
                if self._onDataSent :
                    try :
                        self._onDataSent(self, self._onDataSentArg)
                    except Exception as ex :
                        raise XAsyncTCPClientException('Error when handling the "OnDataSent" event : %s' % ex)
    # ------------------------------------------------------------------------ 
开发者ID:jczic,项目名称:MicroWebSrv2,代码行数:36,代码来源:XAsyncSockets.py


示例28: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def __init__(self, command_cb, address = None, sock_owner = None, backlog = 16, \
      tcp = False, sock_mode = None):
        #print(CLIConnectionManager.__init__, ED2)
        self.command_cb = command_cb
        if not tcp:
            self.serversock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        else:
            self.serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp = tcp
        self.serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if address == None:
            if not tcp:
                address = '/var/run/ccm.sock'
            else:
                address = ('127.0.0.1', 22222)
        if not tcp:
            try:
                remove(address)
            except:
                pass
        self.serversock.bind(address)
        if not tcp:
            if sock_owner != None:
                chown(address, sock_owner[0], sock_owner[1])
            if sock_mode != None:
                chmod(address, sock_mode)
        self.serversock.listen(backlog)
        self.atr = _Acceptor(self) 
开发者ID:sippy,项目名称:rtp_cluster,代码行数:30,代码来源:CLIManager.py


示例29: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import SOL_SOCKET [as 别名]
def __init__(self, global_config, uopts):
        self.uopts = uopts.getCopy()
        self.skt = socket.socket(self.uopts.family, socket.SOCK_DGRAM)
        if self.uopts.laddress != None:
            ai = socket.getaddrinfo(self.uopts.laddress[0], None, self.uopts.family)
            if self.uopts.family == socket.AF_INET:
                address = (ai[0][4][0], self.uopts.laddress[1])
            else:
                address = (ai[0][4][0], self.uopts.laddress[1], ai[0][4][2], ai[0][4][3])
            if (self.uopts.flags & socket.SO_REUSEADDR) != 0:
                self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if hasattr(socket, 'SO_REUSEPORT') and \
              (self.uopts.flags & socket.SO_REUSEPORT) != 0:
                self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            self.skt.bind(address)
            if self.uopts.laddress[1] == 0:
                self.uopts.laddress = self.skt.getsockname()
        self.sendqueue = []
        self.stats = [0, 0, 0]
        self.wi_available = Condition()
        self.wi = []
        self.asenders = []
        self.areceivers = []
        if self.uopts.nworkers == None:
            nworkers = _DEFAULT_NWORKERS
        else:
            nworkers = self.uopts.nworkers
        for i in range(0, nworkers):
            self.asenders.append(AsyncSender(self))
            self.areceivers.append(AsyncReceiver(self)) 
开发者ID:sippy,项目名称:rtp_cluster,代码行数:32,代码来源:Udp_server.py



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