Python socket.TCP_KEEPCNT Examples

The following are 30 code examples of socket.TCP_KEEPCNT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: stream.py    From NoobSec-Toolkit with GNU General Public License v2.0 8 votes vote down vote up
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 
Example #2
Source File: socket_options.py    From Requester with MIT License 6 votes vote down vote up
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
        ) 
Example #3
Source File: stream.py    From backdoorme with MIT License 6 votes vote down vote up
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 
Example #4
Source File: debugger_unittest.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
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 
Example #5
Source File: kubernetes.py    From patroni with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: stream.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #7
Source File: test_connection.py    From aredis with MIT License 6 votes vote down vote up
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() 
Example #8
Source File: server_client.py    From OpenCLGA with MIT License 6 votes vote down vote up
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() 
Example #9
Source File: __init__.py    From aiostratum_proxy with MIT License 5 votes vote down vote up
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) 
Example #10
Source File: grpc_socket.py    From purerpc with Apache License 2.0 5 votes vote down vote up
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) 
Example #11
Source File: agent_server.py    From powerpool with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #12
Source File: bot.py    From Python3-Botnet with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #13
Source File: client.py    From Aoyama with GNU General Public License v2.0 5 votes vote down vote up
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# 
Example #14
Source File: __init__.py    From CUP with Apache License 2.0 5 votes vote down vote up
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 
Example #15
Source File: socket_options.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
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
        ) 
Example #16
Source File: sock.py    From pyp2p with MIT License 5 votes vote down vote up
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) 
Example #17
Source File: __init__.py    From pylutron with MIT License 5 votes vote down vote up
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") 
Example #18
Source File: test_netutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
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)) 
Example #19
Source File: socket_utils.py    From ansible-mikrotik with Apache License 2.0 5 votes vote down vote up
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
    """
    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) 
Example #20
Source File: socket_utils.py    From ansible-mikrotik with Apache License 2.0 5 votes vote down vote up
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
    """
    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) 
Example #21
Source File: RPCClient.py    From aitom with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #22
Source File: api_socket.py    From RouterOS-api with MIT License 5 votes vote down vote up
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) 
Example #23
Source File: ggposrv.py    From ggposrv with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #24
Source File: mtprotoproxy.py    From mtprotoproxy with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: core.py    From ADBHoney with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #26
Source File: aiogps.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
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']) 
Example #27
Source File: ksocket.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #28
Source File: coinhive-stratum-mining-proxy.py    From coinhive-stratum-mining-proxy with MIT License 5 votes vote down vote up
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 
Example #29
Source File: redshift_psql.py    From mycroft with MIT License 5 votes vote down vote up
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 
Example #30
Source File: tcpbanner.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)