Python socket.SO_KEEPALIVE Examples

The following are 30 code examples for showing how to use socket.SO_KEEPALIVE(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: marsnake   Author: turingsec   File: ksocket.py    License: GNU General Public License v3.0 6 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 2
Project: smarthome   Author: smarthomeNG   File: network.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _connect(self):
        self.logger.debug("Connecting to {} using {} {} on TCP port {} {} autoreconnect".format(self._host, 'IPv6' if self._ipver == socket.AF_INET6 else 'IPv4', self._hostip, self._port, ('with' if self._autoreconnect else 'without')))
        # Try to connect to remote host using ip (v4 or v6)
        try:
            self._socket = socket.socket(self._ipver, socket.SOCK_STREAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self._socket.settimeout(5)
            self._socket.connect(('{}'.format(self._hostip), int(self._port)))
            self._socket.settimeout(self._timeout)
            self._is_connected = True
            self.logger.info("Connected to {} on TCP port {}".format(self._host, self._port))
        # Connection error
        except Exception as err:
            self._is_connected = False
            self._connect_counter += 1
            self.logger.warning("TCP connection to {}:{} failed with error {}. Counter: {}/{}".format(self._host, self._port, err, self._connect_counter, self._connect_retries)) 
Example 3
Project: NoobSec-Toolkit   Author: krintoxi   File: stream.py    License: 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 4
Project: NoobSec-Toolkit   Author: krintoxi   File: stream.py    License: 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 5
Project: aredis   Author: NoneGG   File: test_connection.py    License: 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 6
Project: hivemind   Author: steemit   File: http_client.py    License: MIT License 6 votes vote down vote up
def __init__(self, nodes, **kwargs):
        if kwargs.get('tcp_keepalive', True):
            socket_options = HTTPConnection.default_socket_options + \
                             [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), ]
        else:
            socket_options = HTTPConnection.default_socket_options

        self.http = urllib3.poolmanager.PoolManager(
            num_pools=kwargs.get('num_pools', 10),
            maxsize=kwargs.get('maxsize', 64),
            timeout=kwargs.get('timeout', 30),
            socket_options=socket_options,
            block=False,
            retries=Retry(total=False),
            headers={
                'Content-Type': 'application/json',
                'accept-encoding': 'gzip'},
            cert_reqs='CERT_REQUIRED',
            ca_certs=certifi.where())

        self.nodes = cycle(nodes)
        self.url = ''
        self.request = None
        self.next_node() 
Example 7
Project: Requester   Author: kylebebak   File: socket_options.py    License: 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 8
Project: collection   Author: skywind3000   File: asyncredis.py    License: MIT License 6 votes vote down vote up
def connect(self, address, port, timeout = 0):
		self.close()
		af = socket.AF_INET
		if ':' in address:
			if not 'AF_INET6' in socket.__dict__:
				return -1
			if not socket.has_ipv6:
				return -2
			af = socket.AF_INET6
			self.ipv6 = True
		self.sock = socket.socket(af, socket.SOCK_STREAM)
		to = self.sock.gettimeout()
		self.sock.setblocking(0)
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
		self.state = NET_STATE_CONNECTING
		try:
			hr = self.sock.connect_ex((address, port))
		except socket.error, e:
			pass 
Example 9
Project: python-ogn-client   Author: glidernet   File: client.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def connect(self):
        # create socket, connect to server, login and make a file object associated with the socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        if self.aprs_filter:
            port = self.settings.APRS_SERVER_PORT_CLIENT_DEFINED_FILTERS
        else:
            port = self.settings.APRS_SERVER_PORT_FULL_FEED

        self.sock.connect((self.settings.APRS_SERVER_HOST, port))
        self.logger.debug('Server port {}'.format(port))

        login = create_aprs_login(self.aprs_user, -1, self.settings.APRS_APP_NAME, self.settings.APRS_APP_VER, self.aprs_filter)
        self.sock.send(login.encode())
        self.sock_file = self.sock.makefile('rw')

        self._kill = False 
Example 10
Project: masakari   Author: openstack   File: test_wsgi.py    License: Apache License 2.0 6 votes vote down vote up
def test_socket_options_for_simple_server(self):
        # test normal socket options has set properly
        self.flags(tcp_keepidle=500, group='wsgi')
        server = masakari.wsgi.Server("test_socket_options", None,
                                  host="127.0.0.1", port=0)
        server.start()
        sock = server._socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(CONF.wsgi.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        server.stop()
        server.wait() 
Example 11
Project: Uwallet   Author: UlordChain   File: interface.py    License: MIT License 6 votes vote down vote up
def get_simple_socket(self):
        try:
            l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
        except socket.gaierror:
            log.error("cannot resolve hostname")
            return
        for res in l:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.connect(res[4])
                s.settimeout(2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                return s
            except BaseException as e:
                log.exception('Failed to connect to %s', res)
                continue 
Example 12
Project: oslo.service   Author: openstack   File: test_wsgi.py    License: Apache License 2.0 6 votes vote down vote up
def test_socket_options_for_simple_server(self):
        # test normal socket options has set properly
        self.config(tcp_keepidle=500)
        server = wsgi.Server(self.conf, "test_socket_options", None,
                             host="127.0.0.1", port=0)
        server.start()
        sock = server.socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(self.conf.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        self.assertFalse(server._server.dead)
        server.stop()
        server.wait()
        self.assertTrue(server._server.dead) 
Example 13
Project: oslo.service   Author: openstack   File: test_wsgi.py    License: Apache License 2.0 6 votes vote down vote up
def test_socket_options_for_ssl_server(self):
        # test normal socket options has set properly
        self.config(tcp_keepidle=500)
        server = wsgi.Server(self.conf, "test_socket_options", None,
                             host="127.0.0.1", port=0, use_ssl=True)
        server.start()
        sock = server.socket
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_REUSEADDR))
        self.assertEqual(1, sock.getsockopt(socket.SOL_SOCKET,
                                            socket.SO_KEEPALIVE))
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertEqual(CONF.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        server.stop()
        server.wait() 
Example 14
Project: oslo.service   Author: openstack   File: eventlet_service.py    License: Apache License 2.0 6 votes vote down vote up
def start(self, key=None, backlog=128):
        """Run a WSGI server with the given application."""

        if self.socket is None:
            self.listen(key=key, backlog=backlog)

        dup_socket = self.socket.dup()
        if key:
            self.socket_info[key] = self.socket.getsockname()

        # Optionally enable keepalive on the wsgi socket.
        if self.keepalive:
            dup_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

            if self.keepidle is not None:
                dup_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
                                      self.keepidle)

        self.greenthread = self.pool.spawn(self._run,
                                           self.application,
                                           dup_socket) 
Example 15
Project: filebeat.py   Author: iyaozhen   File: filebeat.py    License: MIT License 6 votes vote down vote up
def get_socket(address):
        """
        根据配置信息建立tcp连接
        Args:
            address: host:name字符串

        Returns:
            建立成功返回socket对象, 失败返回False
        """
        (ip, port) = address.split(':')
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  # 在客户端开启心跳维护
        try:
            s.connect((ip, int(port)))
        except socket.error:
            return False
        else:
            return s 
Example 16
Project: Pyro5   Author: irmen   File: socketutil.py    License: MIT License 5 votes vote down vote up
def set_keepalive(sock: socket.socket) -> None:
    """sets the SO_KEEPALIVE option on the socket, if possible."""
    with contextlib.suppress(Exception):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example 17
Project: pycomm3   Author: ottowayi   File: socket_.py    License: MIT License 5 votes vote down vote up
def __init__(self, timeout=5.0):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(timeout)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example 18
Project: RouterOS-api   Author: socialwifi   File: api_socket.py    License: 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 19
Project: purerpc   Author: standy66   File: grpc_socket.py    License: 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 20
Project: sndlatr   Author: Schibum   File: imaplib2.py    License: Apache License 2.0 5 votes vote down vote up
def ssl_wrap_socket(self):

        # Allow sending of keep-alive messages - seems to prevent some servers
        # from closing SSL, leading to deadlocks.
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        try:
            import ssl
            if self.ca_certs is not None:
                cert_reqs = ssl.CERT_REQUIRED
            else:
                cert_reqs = ssl.CERT_NONE

            if self.ssl_version == "tls1":
                ssl_version = ssl.PROTOCOL_TLSv1
            elif self.ssl_version == "ssl2":
                ssl_version = ssl.PROTOCOL_SSLv2
            elif self.ssl_version == "ssl3":
                ssl_version = ssl.PROTOCOL_SSLv3
            elif self.ssl_version == "ssl23" or self.ssl_version is None:
                ssl_version = ssl.PROTOCOL_SSLv23
            else:
                raise socket.sslerror("Invalid SSL version requested: %s", self.ssl_version)

            self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ca_certs=self.ca_certs, cert_reqs=cert_reqs, ssl_version=ssl_version)
            ssl_exc = ssl.SSLError
            self.read_fd = self.sock.fileno()
        except ImportError:
            # No ssl module, and socket.ssl has no fileno(), and does not allow certificate verification
            raise socket.sslerror("imaplib2 SSL mode does not work without ssl module")

        if self.cert_verify_cb is not None:
            cert_err = self.cert_verify_cb(self.sock.getpeercert(), self.host)
            if cert_err:
                raise ssl_exc(cert_err) 
Example 21
Project: ggposrv   Author: poliva   File: ggposrv.py    License: 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 22
Project: Venus   Author: mgsky1   File: InternalMain.py    License: Apache License 2.0 5 votes vote down vote up
def connectClientA(self):
        if not self.clientA:
            self.clientA = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.clientA.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self.clientA.connect((self.fromIP,self.fromPort))
            print('clientA Connected!')
            #将clientA添加进监听可读队列
            self.readableList.append(self.clientA)
    #连接VPS 
Example 23
Project: Venus   Author: mgsky1   File: InternalMain.py    License: Apache License 2.0 5 votes vote down vote up
def connectClientB(self):
        if not self.clientB:
            self.clientB = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.clientB.setsockopt(socket.SOL_SOCKET,socket.SO_KEEPALIVE,1)
            self.clientB.connect((self.remoteIp, self.remotePort))
            print('clientB Connected!')
            # 将client添加进监听可读队列
            self.readableList.append(self.clientB)
    #关闭clientA 
Example 24
Project: Venus   Author: mgsky1   File: InternalMain.py    License: Apache License 2.0 5 votes vote down vote up
def InternalMain(remoteIP,commonPort,remotePort,localIp,localPort):
    #remoteIP ->远程VPS的IP地址
    #commonPort -> 心跳检测端口
    #remotePort -> 远程VPS数据监听端口
    #localIp -> 本地IP
    #localPort -> 本地端口
    #clientC专门与远程VPS做心跳
    clientC = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientC.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    clientC.connect((remoteIP, commonPort))
    rl = [clientC]
    #监听
    while True:
        rs, ws, es = select.select(rl, [], [])
        for each in rs:
            if each == clientC:
                tdataC = each.recv(1024)
                if not tdataC:
                    rl.remove(clientC)
                    clientC.close()
                    clientC.connect((remoteIP, commonPort))
                    rl = [clientC]
                    break
                if DEBUG:
                    print(tdataC)
                #若远程VPS接收到用户访问请求,则激活一个线程用于处理
                if tdataC == bytes('ACTIVATE',encoding='utf-8'):
                    foo = MappingClient(localIp,localPort,'tcp',remoteIP,remotePort)
                    t = Thread(target=foo.TCPMapping)
                    t.setDaemon(True)
                    t.start()
                #心跳检测
                elif tdataC == bytes('IAMALIVE',encoding='utf-8'):
                    b = bytes('OK', encoding='utf-8')
                    each.send(b) 
Example 25
Project: pyvisa-py   Author: pyvisa   File: tcpip.py    License: MIT License 5 votes vote down vote up
def _get_tcpip_keepalive(self, attribute):
        if self.interface:
            value = self.interface.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)
            return (
                constants.VI_TRUE if value == 1 else constants.VI_FALSE,
                StatusCode.success,
            )
        return 0, StatusCode.error_nonsupported_attribute 
Example 26
Project: pyvisa-py   Author: pyvisa   File: tcpip.py    License: MIT License 5 votes vote down vote up
def _set_tcpip_keepalive(self, attribute, attribute_state):
        if self.interface:
            self.interface.setsockopt(
                socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 if attribute_state else 0
            )
            return StatusCode.success
        return 0, StatusCode.error_nonsupported_attribute 
Example 27
Project: mtprotoproxy   Author: alexbers   File: mtprotoproxy.py    License: 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 28
Project: ADBHoney   Author: huuck   File: core.py    License: 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 29
Project: rtkbase   Author: Stefal   File: aiogps.py    License: 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 30
Project: PyDev.Debugger   Author: fabioz   File: debugger_unittest.py    License: Eclipse Public License 1.0 5 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