Python socket.SO_KEEPALIVE() Examples

The following are code examples for showing how to use socket.SO_KEEPALIVE(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: python-ogn-client   Author: glidernet   File: client.py    (license) View Source Project 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 = settings.APRS_SERVER_PORT_CLIENT_DEFINED_FILTERS
        else:
            port = settings.APRS_SERVER_PORT_FULL_FEED

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

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

        self._kill = False 
Example 2
Project: pupy   Author: ru-faraon   File: clients.py    (license) View Source Project 6 votes vote down vote up
def connect(self, host, port):
        family, socktype, proto, _, sockaddr = socket.getaddrinfo(host, port, self.family, self.socktype)[0]
        s = socket.socket(family, socktype, proto)
        s.settimeout(self.timeout)
        s.connect(sockaddr)
        if self.nodelay:
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        if self.keepalive:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            # Linux specific: after 1 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, 1 * 60)
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5 * 60)
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 10)
        self.sock=s
        return s 
Example 3
Project: pupy   Author: ru-faraon   File: clients.py    (license) View Source Project 6 votes vote down vote up
def connect(self, host, port):
        s = socks.socksocket()
        s.setproxy(proxy_type=socks.PROXY_TYPES[self.proxy_type], addr=self.proxy_addr, port=self.proxy_port, rdns=True, username=self.proxy_username, password=self.proxy_password)
        s.settimeout(self.timeout)
        s.connect((host,port))
        if self.nodelay:
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        if self.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)
        self.sock=s
        return s 
Example 4
Project: flickr_downloader   Author: Denisolt   File: socket_options.py    (license) View Source Project 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 5
Project: autoreg   Author: pbeyssac   File: query.py    (license) View Source Project 6 votes vote down vote up
def handleclient(self, c, a):
    w = socketwrapper(c)
    sys.stdout = w
    ip, cport, flowinfo, scopeid = a
    c.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    q = ''
    r = c.recv(256)
    while r:
      q += r
      i = q.find('\r\n')
      if i >= 0:
        q = q[:i]
        if ip.startswith('::ffff:'):
              ip = ip[7:]
        self.log("%s %s" % (ip, q))
        # XXX: the 192.168.0.* check is a terrible hack until the
        # Perl query interface is rewritten.
        query(q, self.dbstring, w,
              remote = (ip != '127.0.0.1' and ip != '::1'
                        and not ip.startswith('192.168.0.')))
        c.shutdown(socket.SHUT_WR)
        break
      r = c.recv(256)
    c.close() 
Example 6
Project: Liljimbo-Chatbot   Author: chrisjim316   File: socket_options.py    (license) View Source Project 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 7
Project: mcg   Author: coderkun   File: client.py    (license) View Source Project 6 votes vote down vote up
def _connect_socket(self, host, port):
        sock = None
        error = None
        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP):
            af, socktype, proto, canonname, sa = res
            try:
                sock = socket.socket(af, socktype, proto)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                sock.connect(sa)
                return sock
            except Exception as e:
                error = e
                if sock is not None:
                    sock.close()
                break
        if error is not None:
            raise ConnectionException("connection failed: {}".format(error))
        else:
            raise ConnectionException("no suitable socket") 
Example 8
Project: OpenCLGA   Author: PyOCL   File: server_client.py    (license) View Source Project 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
Project: alfred-mpd   Author: valrus   File: mpd.py    (license) View Source Project 6 votes vote down vote up
def _connect_tcp(self, host, port):
        try:
            flags = socket.AI_ADDRCONFIG
        except AttributeError:
            flags = 0
        err = None
        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM, socket.IPPROTO_TCP,
                                      flags):
            af, socktype, proto, canonname, sa = res
            sock = None
            try:
                sock = socket.socket(af, socktype, proto)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                sock.settimeout(self.timeout)
                sock.connect(sa)
                return sock
            except socket.error as e:
                err = e
                if sock is not None:
                    sock.close()
        if err is not None:
            raise err
        else:
            raise ConnectionError("getaddrinfo returns an empty list") 
Example 10
Project: lbryum   Author: lbryio   File: interface.py    (license) View Source Project 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 11
Project: denite.nvim   Author: Shougo   File: socket.py    (license) View Source Project 6 votes vote down vote up
def connect(self, host, port, timeout):
        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM, socket.IPPROTO_TCP,
                                      socket.AI_ADDRCONFIG):
            family, socket_type, proto, canon_name, sa = res
            sock = None
            try:
                sock = socket.socket(family, socket_type, proto)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                sock.settimeout(timeout)
                sock.connect(sa)
                return sock
            except socket.error as e:
                if sock is not None:
                    sock.close()

                if e is not None:
                    raise e
                else:
                    raise OSError('Socket: getaddrinfo returns an empty list') 
Example 12
Project: RuneAudioLCDMod   Author: lukazgur   File: mpd.py    (license) View Source Project 6 votes vote down vote up
def _connect_tcp(self, host, port):
        try:
            flags = socket.AI_ADDRCONFIG
        except AttributeError:
            flags = 0
        err = None
        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM, socket.IPPROTO_TCP,
                                      flags):
            af, socktype, proto, canonname, sa = res
            sock = None
            try:
                sock = socket.socket(af, socktype, proto)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                sock.settimeout(self.timeout)
                sock.connect(sa)
                return sock
            except socket.error as e:
                err = e
                if sock is not None:
                    sock.close()
        if err is not None:
            raise err
        else:
            raise ConnectionError("getaddrinfo returns an empty list") 
Example 13
Project: OctoFusion   Author: tapnair   File: socket_options.py    (license) View Source Project 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 14
Project: masakari   Author: openstack   File: test_wsgi.py    (license) View Source Project 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 15
Project: glare   Author: openstack   File: test_wsgi.py    (license) View Source Project 6 votes vote down vote up
def test_correct_configure_socket(self):
        mock_socket = mock.Mock()
        self.useFixture(fixtures.MonkeyPatch(
            'glare.common.wsgi.ssl.wrap_socket',
            mock_socket))
        self.useFixture(fixtures.MonkeyPatch(
            'glare.common.wsgi.eventlet.listen',
            lambda *x, **y: mock_socket))
        server = wsgi.Server()
        server.default_port = 1234
        server.configure_socket()
        self.assertIn(mock.call.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_REUSEADDR,
            1), mock_socket.mock_calls)
        self.assertIn(mock.call.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_KEEPALIVE,
            1), mock_socket.mock_calls)
        if hasattr(socket, 'TCP_KEEPIDLE'):
            self.assertIn(mock.call().setsockopt(
                socket.IPPROTO_TCP,
                socket.TCP_KEEPIDLE,
                wsgi.CONF.tcp_keepidle), mock_socket.mock_calls) 
Example 16
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_wsgi.py    (license) View Source Project 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 = nova.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 17
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_wsgi.py    (license) View Source Project 6 votes vote down vote up
def test_socket_options_for_ssl_server(self):
        # test normal socket options has set properly
        self.flags(tcp_keepidle=500, group='wsgi')
        server = nova.wsgi.Server("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.wsgi.tcp_keepidle,
                             sock.getsockopt(socket.IPPROTO_TCP,
                                             socket.TCP_KEEPIDLE))
        server.stop()
        server.wait() 
Example 18
Project: gimel   Author: Alephbet   File: connection.py    (MIT License) View Source Project 5 votes vote down vote up
def _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list") 
Example 19
Project: sndlatr   Author: Schibum   File: imaplib2.py    (Apache License 2.0) View Source Project 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 20
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connection.py    (MIT License) View Source Project 5 votes vote down vote up
def _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list") 
Example 21
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connection.py    (MIT License) View Source Project 5 votes vote down vote up
def _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list") 
Example 22
Project: sauna   Author: NicolasLM   File: tcp_server.py    (BSD 2-Clause "Simplified" License) View Source Project 5 votes vote down vote up
def _activate_keepalive(self, s, after_idle_sec=30, interval_sec=10,
                            max_fails=5):
        """Set TCP keepalive on an open socket.

        It activates after 30 second (after_idle_sec) of idleness,
        then sends a keepalive ping once every 10 seconds (interval_sec),
        and closes the connection after 5 failed ping (max_fails).
        """
        s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails) 
Example 23
Project: ave   Author: sonyxperiadev   File: connection.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def set_keepalive(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 5)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) 
Example 24
Project: ave   Author: sonyxperiadev   File: connection.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def set_keepalive(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 5)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) 
Example 25
Project: Tinychat-Bot--Discontinued   Author: Tinychat   File: rtmp.py    (MIT License) View Source Project 5 votes vote down vote up
def connect(self, connect_params=None):
        """ Connect to the remote server with the given connect parameters.

        :param connect_params: A list or dict containing application specific connect parameters
        :type connect_params: list | dict
        """
        if self.proxy:
            parts = self.proxy.split(':')
            ip = parts[0]
            port = int(parts[1])

            ps = socks.socksocket()
            ps.set_proxy(socks.HTTP, addr=ip, port=port)
            self.socket = ps
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.socket.connect((self.ip, self.port))
        self.file = self.socket.makefile()
        self.stream = FileDataTypeMixIn(self.file)

        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if self.is_win:
            self.socket.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))

        self.handshake()

        self.reader = reader.RtmpReader(self.stream)
        self.writer = writer.RtmpWriter(self.stream)

        self._connect_rtmp(connect_params) 
Example 26
Project: health-mosconi   Author: GNUHealth-Mosconi   File: webdav.py    (license) View Source Project 5 votes vote down vote up
def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET,
                socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.SOL_SOCKET,
            socket.SO_KEEPALIVE, 1)
        BaseHTTPServer.HTTPServer.server_bind(self) 
Example 27
Project: health-mosconi   Author: GNUHealth-Mosconi   File: xmlrpc.py    (license) View Source Project 5 votes vote down vote up
def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET,
                socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.SOL_SOCKET,
            socket.SO_KEEPALIVE, 1)
        SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self) 
Example 28
Project: health-mosconi   Author: GNUHealth-Mosconi   File: jsonrpc.py    (license) View Source Project 5 votes vote down vote up
def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET,
                socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.SOL_SOCKET,
            socket.SO_KEEPALIVE, 1)
        SimpleJSONRPCServer.server_bind(self) 
Example 29
Project: hostapd-mana   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 30
Project: hostapd-mana   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 31
Project: hostapd-mana   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)) 
Example 32
Project: hostapd-mana   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 33
Project: deb-oslo.utils   Author: openstack   File: test_netutils.py    (license) View Source Project 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 34
Project: crispy-fortnight   Author: hansjhoffman   File: client_type.py    (license) View Source Project 5 votes vote down vote up
def connect(self, host, port):
        family, socktype, proto, _, sockaddr = socket.getaddrinfo(host, port, self.family, self.sock_type, self.protocol)[0]
        s = socket.socket(family, socktype, proto)
        s.settimeout(self.timeout)
        s.connect(sockaddr)

        if self.nodelay:
            s.setsockopt(self.protocol, socket.TCP_NODELAY, 1)

        if self.keepalive:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        self.sock = s
        return s 
Example 35
Project: aiomongo   Author: ZeoAlliance   File: connection.py    (license) View Source Project 5 votes vote down vote up
def connect(self) -> None:
        if self.host.startswith('/'):
            self.reader, self.writer = await asyncio.open_unix_connection(
                path=self.host, loop=self.loop
            )
        else:
            self.reader, self.writer = await asyncio.open_connection(
                host=self.host, port=self.port, loop=self.loop
            )

        sock = self.writer.transport.get_extra_info('socket')
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, int(self.options.pool_options.socket_keepalive))

        if self.host.startswith('/'):
            endpoint = self.host
        else:
            endpoint = '{}:{}'.format(self.host, self.port)
        logger.debug('Established connection to {}'.format(endpoint))
        self.read_loop_task = asyncio.ensure_future(self.read_loop(), loop=self.loop)

        ismaster = IsMaster(await self.command(
            'admin', SON([('ismaster', 1)]), ReadPreference.PRIMARY, DEFAULT_CODEC_OPTIONS
        ))

        self.is_mongos = ismaster.server_type == SERVER_TYPE.Mongos
        self.max_wire_version = ismaster.max_wire_version
        if ismaster.max_bson_size:
            self.max_bson_size = ismaster.max_bson_size
        if ismaster.max_message_size:
            self.max_message_size = ismaster.max_message_size
        if ismaster.max_write_batch_size:
            self.max_write_batch_size = ismaster.max_write_batch_size
        self.is_writable = ismaster.is_writable

        self.slave_ok = not self.is_mongos and self.options.read_preference != ReadPreference.PRIMARY

        if self.options.credentials:
            await self._authenticate()

        # Notify waiters that connection has been established
        self.__connected.set() 
Example 36
Project: SameKeyProxy   Author: xzhou   File: protocol.py    (license) View Source Project 5 votes vote down vote up
def set_sock_keepalive(sock):
	if Pyro.config.PYRO_SOCK_KEEPALIVE:
		try:
			sock.setsockopt ( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 )
		except:
			Pyro.config.PYRO_SOCK_KEEPALIVE=0    # it didn't work--disable keepalives.


#------ PYRO: adapter (default Pyro wire protocol)
#------ This adapter is for protocol version 4 ONLY
# Future adapters could be downwards compatible and more flexible. 
Example 37
Project: Tinychat-Bot-Minimal--Discontinued   Author: Tinychat   File: rtmp.py    (license) View Source Project 5 votes vote down vote up
def connect(self, connect_params=None):
        """ Connect to the remote server with the given connect parameters.

        :param connect_params: A list or dict containing application specific connect parameters
        :type connect_params: list | dict
        """
        if self.proxy:
            parts = self.proxy.split(':')
            ip = parts[0]
            port = int(parts[1])

            ps = socks.socksocket()
            ps.set_proxy(socks.HTTP, addr=ip, port=port)
            self.socket = ps
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.socket.connect((self.ip, self.port))
        self.file = self.socket.makefile()
        self.stream = FileDataTypeMixIn(self.file)

        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if self.is_win:
            self.socket.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))

        self.handshake()

        self.reader = reader.RtmpReader(self.stream)
        self.writer = writer.RtmpWriter(self.stream)

        self._connect_rtmp(connect_params) 
Example 38
Project: sbds   Author: steemit   File: http_client.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, url=None, log_level=logging.INFO, **kwargs):
        url = url or os.environ.get('STEEMD_HTTP_URL')
        self.url = url
        self.hostname = urlparse(url).hostname
        self.return_with_args = kwargs.get('return_with_args', False)
        self.re_raise = kwargs.get('re_raise', False)
        self.max_workers = kwargs.get('max_workers', None)

        num_pools = kwargs.get('num_pools', 10)
        maxsize = kwargs.get('maxsize', 10)
        timeout = kwargs.get('timeout', 60)
        retries = kwargs.get('retries', 30)
        pool_block = kwargs.get('pool_block', False)
        tcp_keepalive = kwargs.get('tcp_keepalive', True)

        if tcp_keepalive:
            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=num_pools,
            maxsize=maxsize,
            block=pool_block,
            timeout=timeout,
            retries=retries,
            socket_options=socket_options,
            headers={'Content-Type': 'application/json'},
            cert_reqs='CERT_REQUIRED',
            ca_certs=certifi.where())
        '''
            urlopen(method, url, body=None, headers=None, retries=None,
            redirect=True, assert_same_host=True, timeout=<object object>,
            pool_timeout=None, release_conn=None, chunked=False, body_pos=None,
            **response_kw)
        '''
        self.request = partial(self.http.urlopen, 'POST', url)

        _logger = sbds.sbds_logging.getLogger('urllib3')
        sbds.sbds_logging.configure_existing_logger(_logger, level=log_level) 
Example 39
Project: paraproxio   Author: intagger   File: paraproxio.py    (license) View Source Project 5 votes vote down vote up
def tcp_keepalive(server, transport):
        sock = transport.get_extra_info('socket')
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example 40
Project: ballade   Author: shawn1m   File: utils.py    (license) View Source Project 5 votes vote down vote up
def set_socket(s, keep_alive=False):
    # TCP socket keep alive
    if keep_alive and sys.platform == "linux":
        s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 30)
        s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 5)
        s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 3) 
Example 41
Project: Peppy   Author: project-owner   File: mpdconnection.py    (license) View Source Project 5 votes vote down vote up
def try_to_connect(self):
        """ Connect to MPD socket """
        
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self.socket.connect((self.host, self.port))
            self.reader = self.socket.makefile(self.reader_flags, encoding=self.character_encoding)
            self.writer = self.socket.makefile(self.writer_flags, encoding=self.character_encoding)
            self.read_line()
        except:
            if self.socket: 
                self.disconnect()
                return False
        return True 
Example 42
Project: etfa2015   Author: avoyages   File: modbus_tcp_b.py    (license) View Source Project 5 votes vote down vote up
def set_keepalive(self,_sock, after_idle_sec=5, interval_sec=3, max_fails=60):
        """Set TCP keepalive on an open socket.--new add

        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 60 failed ping (max_fails), or 180 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 43
Project: 5In1RowService   Author: caiwb   File: netstream.py    (license) View Source Project 5 votes vote down vote up
def connect(self, address, port, head = -1, block = False, timeout = 0):
		self.close()
		self.block = block
		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()
		if not self.block:
			self.sock.setblocking(0)
		elif timeout > 0:
			self.sock.settimeout(timeout)
		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:
			if self.block:
				self.close()
				return -3
		if self.block and hr != 0:
			return -4
		if self.block and timeout > 0:
			self.sock.settimeout(to)
		self.send_buf = ''
		self.recv_buf = ''
		self.errc = 0
		if head >= 0 and head <= 14:
			self.__head_init(head)
		if self.block:
			self.state = NET_STATE_ESTABLISHED
		return 0

	# close connection 
Example 44
Project: 5In1RowService   Author: caiwb   File: netstream.py    (license) View Source Project 5 votes vote down vote up
def assign(self, sock, head = -1, block = False):
		self.close()
		self.block = block
		self.sock = sock
		self.sock.setblocking(self.block and 1 or 0)
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
		self.state = NET_STATE_ESTABLISHED
		if head >= 0 and head <= 14:
			self.__head_init(head)
		self.send_buf = ''
		self.recv_buf = ''
		return 0
	
	# update 
Example 45
Project: 5In1RowService   Author: caiwb   File: netstream.py    (license) View Source Project 5 votes vote down vote up
def keepalive (self, keepalive = 0):
		if not 'SO_KEEPALIVE' in socket.__dict__:
			return -1
		if self.sock == None:
			return -2
		try:
			self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, keepalive)
		except:
			return -3
		return 0
	
	# set rc4 key for sending encryption 
Example 46
Project: sslstrip-hsts-openwrt   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 47
Project: sslstrip-hsts-openwrt   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 48
Project: sslstrip-hsts-openwrt   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)) 
Example 49
Project: sslstrip-hsts-openwrt   Author: adde88   File: tcp.py    (license) View Source Project 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 50
Project: pycon2016   Author: nhudinhtuan   File: gtcpasyncclient.py    (license) View Source Project 5 votes vote down vote up
def _set_keep_alive(self):
		stream_socket = self._stream.socket
		stream_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
		if platform.system().lower() == 'linux':
			stream_socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 30)
			stream_socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 5)
			stream_socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 5)