Python socket.SO_KEEPALIVE() Examples

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

Example 1
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_wsgi.py    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 = 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 2
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_wsgi.py    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.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 3
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: socket.py    MIT License 6 votes vote down vote up
def apply(self, sock):
        """Set the keepalive values on the socket."""
        sock.setsockopt(socket.SOL_SOCKET,
                        socket.SO_KEEPALIVE,
                        1)
        interval = self.interval
        idle = self.idle
        maxfails = self.maxfails
        try:
            if interval > 0:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPINTVL,
                                interval)
            if idle > 0:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPIDLE,
                                idle)
            if maxfails >= 0:
                sock.setsockopt(socket.IPPROTO_TCP,
                                socket.TCP_KEEPCNT,
                                maxfails)
        except AttributeError:
            # mostly linux-only
            pass 
Example 4
Project: nova   Author: ZhanHan   File: test_wsgi.py    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 = 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 5
Project: nova   Author: ZhanHan   File: test_wsgi.py    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.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 6
Project: atavism   Author: zathras777   File: client.py    The Unlicense 6 votes vote down vote up
def _make_socket(self):
        """ Create a new connected socket.
        :raise HttpClientError:
        """
        if self.socket is None:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            sock.settimeout(5)
            try:
                sock.connect((str(self.host), self.port))
                sock.settimeout(30)
                self.socket = sock
            except socket.error:
                raise HttpClientError("Attempt to connect to '{}' on port {} failed".format(self.host, self.port))
            except socket.timeout:
                raise HttpClientError("Attempt to connect to '{}' on port {} timed out".format(self.host, self.port))
            except socket.gaierror:
                raise HttpClientError("Unable to resolve host '{}'".format(self.host)) 
Example 7
Project: extensiveautomation-server   Author: ExtensiveAutomation   File: TcpServer.py    GNU Lesser General Public License v2.1 6 votes vote down vote up
def handle(self):
        """
        BaseRequestHandler Reimplentation
        """
        self.socket = self.request
        self.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        while not self.stopEvent.isSet():
            try:
                self.mainReceiveSendLoop()
            except NoMoreData as e:
                self.trace("handle no more data: %s" % e)
                self.stop()
            except Exception as e:
                self.error("unable to handle tcp client thread: %s" % e)
                self.stop() 
Example 8
Project: marsnake   Author: turingsec   File: ksocket.py    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 9
Project: smarthome   Author: smarthomeNG   File: network.py    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 10
Project: stx-nova   Author: starlingx-staging   File: test_wsgi.py    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 = 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 11
Project: stx-nova   Author: starlingx-staging   File: test_wsgi.py    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.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 12
Project: uwallet-client   Author: UlordChain   File: interface.py    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 13
Project: geofire-python   Author: ininex   File: socket_options.py    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 14
Project: SurfCity   Author: cn-uofbasel   File: net.py    MIT License 6 votes vote down vote up
def connect(host, port, feedID, keypair):
    # from ssb-caps.js: 
    #   Buffer('1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=', 'base64')
    appKey = base64.b64decode('1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=')
    client = SHSClient(host, port, keypair, base64.b64decode(feedID[1:-8]),
                       application_key=appKey)
    packet_stream = PacketStream(client)
    await client.open()

    s = client.writer._protocol._stream_reader._transport._extra['socket']
    if sys.platform == 'darwin':
        TCP_KEEPALIVE = 0x10
        s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        s.setsockopt(socket.IPPROTO_TCP, TCP_KEEPALIVE, 2) # after_idle_sec
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5) # interval_sec
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
    elif sys.platform == 'linux':
        s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 2) # after_idle_sec
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5) # interval_sec
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) # max_fails
    
    api.add_connection(packet_stream)
    return api 
Example 15
Project: btcnano-wallet-client-desktop   Author: bitcoinnano   File: interface.py    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:
            self.print_error("cannot resolve hostname")
            return
        e = None
        for res in l:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.settimeout(10)
                s.connect(res[4])
                s.settimeout(2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                return s
            except BaseException as _e:
                e = _e
                continue
        else:
            self.print_error("failed to connect", str(e)) 
Example 16
Project: RealTimeOpenControl   Author: Haschtl   File: jsonsocket.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, host, port, keyword=None, reuse_port=True, timeout=5):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client = None

        if reuse_port:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        # if hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") and hasattr(socket, "TCP_KEEPCNT"):
        #     self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1 * 60)
        #     self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5 * 60)
        #     self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 10)
        # self.socket.setblocking(0)
        self.socket.settimeout(timeout)
        self.socket.bind((host, port))
        self.socket.listen(BACKLOG)

        self.keyword = keyword 
Example 17
Project: RealTimeOpenControl   Author: Haschtl   File: jsonsocket.py    GNU General Public License v3.0 6 votes vote down vote up
def connect(self, host, port, keyword=None, reuse_port=True, timeout=5):
        """
        Establish a connection to a host (server)

        Args:
            host (str): Hostname (e.g. 0.0.0.0)
            port (int): Port to bind tcp-socket (e.g. 5050)
            keyword (str or None): Set a keyword for encrypted communication. Leaf blank for unsecure connection. (default: None)
            reuse_port (bool): Enable/disable reuse_port (default: True)
        """
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        if reuse_port:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        # self.socket.setblocking(0)
        self.socket.settimeout(timeout)
        self.socket.connect((host, port))
        self.keyword = keyword
        self.host = host
        return self 
Example 18
Project: ngo-addons-backport   Author: camptocamp   File: netrpc_socket.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock
        # self.sock.settimeout(120)
        # prepare this socket for long operations: it may block for infinite
        # time, but should exit as soon as the net is down
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example 19
Project: AvereSDK   Author: Azure   File: xmlrpcClt.py    MIT License 5 votes vote down vote up
def init_poolmanager(self, *args, **kwargs): #pylint: disable=arguments-differ
            kwargs['socket_options'] = [
                (socket.SOL_TCP, socket.TCP_NODELAY, 1),     # disable Nagle algorithm and send small requests immediately
                (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), # check for dead servers
                (socket.SOL_TCP, socket.TCP_KEEPINTVL, 15),  # probe every 15 seconds
                (socket.SOL_TCP, socket.TCP_KEEPCNT, 8),     # up to 8 attempts == 120 seconds
            ]
            super(RequestsTransport.CustomAdapter, self).init_poolmanager(*args, **kwargs) 
Example 20
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevd_comm.py    MIT License 5 votes vote down vote up
def start_client(host, port):
    ''' connects to a host/port '''
    pydev_log.info("Connecting to %s:%s", host, port)

    s = socket(AF_INET, 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(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.

    try:
        # 10 seconds default timeout
        timeout = int(os.environ.get('PYDEVD_CONNECT_TIMEOUT', 10))
        s.settimeout(timeout)
        s.connect((host, port))
        s.settimeout(None)  # no timeout after connected
        pydev_log.info("Connected.")
        return s
    except:
        pydev_log.exception("Could not connect to %s: %s", host, port)
        raise 
Example 21
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: debugger_unittest.py    MIT License 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(6):
            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 22
Project: xm2cloud_transport   Author: forcemain   File: client.py    GNU General Public License v3.0 5 votes vote down vote up
def re_connect(cls, host, port):
        cls.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        cls.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        cls.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        cls.sock.connect((host, port)) 
Example 23
Project: xm2cloud_transport   Author: forcemain   File: client.py    GNU General Public License v3.0 5 votes vote down vote up
def re_connect(cls, host, port):
        cls.nonce = None
        cls.token = None
        cls.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        cls.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        cls.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        cls.sock.connect((host, port)) 
Example 24
Project: beowulf-python   Author: beowulf-foundation   File: http_client.py    MIT License 5 votes vote down vote up
def __init__(self, nodes, **kwargs):
        self.re_raise = kwargs.get('re_raise', True)
        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', 20)
        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.nodes = cycle(self.sanitize_nodes(nodes))
        self.url = ''
        self.request = None
        self.next_node()

        log_level = kwargs.get('log_level', logging.INFO)
        logger.setLevel(log_level) 
Example 25
Project: redis-marshal   Author: mitjafelicijan   File: connection.py    MIT License 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, self.socket_type,
                                      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 26
Project: aiotunnel   Author: codepr   File: protocol.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connection_made(self, transport):
        self.transport = transport
        self.transport.set_write_buffer_limits(0)
        sock = transport.get_extra_info('socket')
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example 27
Project: Pyro5   Author: irmen   File: socketutil.py    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 28
Project: pycomm3   Author: ottowayi   File: socket_.py    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 29
Project: grand_central   Author: amiracle   File: args.py    MIT License 5 votes vote down vote up
def _compute_socket_options(self, scoped_config):
        # This disables Nagle's algorithm and is the default socket options
        # in urllib3.
        socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
        if scoped_config:
            # Enables TCP Keepalive if specified in shared config file.
            if self._ensure_boolean(scoped_config.get('tcp_keepalive', False)):
                socket_options.append(
                    (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1))
        return socket_options 
Example 30
Project: redis-py-threaded   Author: paepcke   File: connection.py    MIT License 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 31
Project: redis-py-threaded   Author: paepcke   File: threadedConnection.py    MIT License 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 32
Project: mks   Author: rgerganov   File: authd.py    MIT License 5 votes vote down vote up
def handshake(host, port, ticket, cfg_file, thumbprint):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    expect(sock, VMAD_WELCOME)
    sock = ssl.wrap_socket(sock)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    cert = sock.getpeercert(binary_form=True)
    h = hashlib.sha1()
    h.update(cert)
    if thumbprint != h.hexdigest():
        raise Exception("Server thumbprint doesn't match")
    sock.write("%s %s\r\n" % (VMAD_USER_CMD, ticket))
    expect(sock, VMAD_NEEDPASSWD)
    sock.write("%s %s\r\n" % (VMAD_PASS_CMD, ticket))
    expect(sock, VMAD_LOGINOK)
    rand = os.urandom(12)
    rand = base64.b64encode(rand)
    sock.write("%s %s\r\n" % (VMAD_THUMB_CMD, rand))
    thumbprint2 = expect(sock, VMAD_OK)
    thumbprint2 = thumbprint2.replace(':', '').lower()
    sock.write("%s %s mks\r\n" % (VMAD_CONNECT_CMD, cfg_file))
    expect(sock, VMAD_OK)
    sock2 = ssl.wrap_socket(sock)
    cert2 = sock2.getpeercert(binary_form=True)
    h = hashlib.sha1()
    h.update(cert2)
    if thumbprint2 != h.hexdigest():
        raise Exception("Second thumbprint doesn't match")
    sock2.write(rand)
    return sock2 
Example 33
Project: unhuman-resources   Author: agajdosi   File: tcp_helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def tcp_keepalive(transport: asyncio.Transport) -> None:
        sock = transport.get_extra_info('socket')
        if sock is not None:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example 34
Project: unhuman-resources   Author: agajdosi   File: tcp_helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def tcp_keepalive(transport: asyncio.Transport) -> None:
        sock = transport.get_extra_info('socket')
        if sock is not None:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example 35
Project: purerpc   Author: standy66   File: grpc_socket.py    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)
        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 36
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 37
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 38
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 39
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 40
Project: pygears   Author: bogdanvuk   File: pywave_server.py    MIT License 5 votes vote down vote up
def set_keepalive_linux(sock, after_idle_sec=1, interval_sec=1, max_fails=3):
    """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 41
Project: sndlatr   Author: Schibum   File: imaplib2.py    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 42
Project: Venus   Author: mgsky1   File: InternalMain.py    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 43
Project: Venus   Author: mgsky1   File: InternalMain.py    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 44
Project: Venus   Author: mgsky1   File: InternalMain.py    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 45
Project: xenascriptlibs   Author: xenadevel   File: SocketDrivers.py    MIT License 5 votes vote down vote up
def set_keepalives(self):
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 2) 
Example 46
Project: xenascriptlibs   Author: xenadevel   File: SocketDrivers.py    MIT License 5 votes vote down vote up
def set_keepalives(self):
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 2) 
Example 47
Project: Tinychat-Bot--Discontinued   Author: Tinychat   File: rtmp.py    MIT License 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 48
Project: mtprotoproxy   Author: alexbers   File: mtprotoproxy.py    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 49
Project: ADBHoney   Author: huuck   File: core.py    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 50
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    GNU General Public License v2.0 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 51
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    GNU General Public License v2.0 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 52
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    GNU General Public License v2.0 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 53
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    GNU General Public License v2.0 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 54
Project: satori   Author: leancloud   File: connection.py    Apache License 2.0 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 55
Project: hackathon   Author: vertica   File: connection.py    Apache License 2.0 5 votes vote down vote up
def _socket(self):
        if self.socket is not None:
            return self.socket

        host = self.options.get('host')
        port = self.options.get('port')
        raw_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        raw_socket.connect((host, port))

        ssl_options = self.options.get('ssl')
        if ssl_options is not None and ssl_options is not False:
            from ssl import CertificateError, SSLError
            raw_socket.sendall(messages.SslRequest().to_bytes())
            response = raw_socket.recv(1)
            if response in ('S', b'S'):
                try:
                    if isinstance(ssl_options, ssl.SSLContext):
                        raw_socket = ssl_options.wrap_socket(raw_socket, server_hostname=host)
                    else:
                        raw_socket = ssl.wrap_socket(raw_socket)
                except CertificateError as e:
                    raise errors.ConnectionError('SSL: ' + e.message)
                except SSLError as e:
                    raise errors.ConnectionError('SSL: ' + e.reason)
            else:
                raise SSLNotSupported("SSL requested but not supported by server")

        self.socket = raw_socket
        return self.socket 
Example 56
Project: eclcli   Author: nttcom   File: client.py    Apache License 2.0 5 votes vote down vote up
def init_poolmanager(self, *args, **kwargs):
        if requests.__version__ >= '2.4.1':
            kwargs.setdefault('socket_options', [
                (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),
                (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
            ])
        super(TCPKeepAliveAdapter, self).init_poolmanager(*args, **kwargs) 
Example 57
Project: eclcli   Author: nttcom   File: client.py    Apache License 2.0 5 votes vote down vote up
def init_poolmanager(self, *args, **kwargs):
        if requests.__version__ >= '2.4.1':
            kwargs.setdefault('socket_options', [
                (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),
                (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
            ])
        super(TCPKeepAliveAdapter, self).init_poolmanager(*args, **kwargs) 
Example 58
Project: eclcli   Author: nttcom   File: client.py    Apache License 2.0 5 votes vote down vote up
def init_poolmanager(self, *args, **kwargs):
        if requests.__version__ >= '2.4.1':
            kwargs.setdefault('socket_options', [
                (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),
                (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
            ])
        super(TCPKeepAliveAdapter, self).init_poolmanager(*args, **kwargs) 
Example 59
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connection.py    MIT License 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 60
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connection.py    MIT License 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 61
Project: imapfetch-idle   Author: neverpanic   File: imaplib2.py    BSD 3-Clause "New" or "Revised" License 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(binary_form=True), self.host)
            if cert_err:
                raise ssl_exc(cert_err) 
Example 62
Project: coinhive-stratum-mining-proxy   Author: x25   File: coinhive-stratum-mining-proxy.py    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 63
Project: irwin   Author: clarkerubber   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_keepalive_adapter():
    return HTTPAdapterWithSocketOptions(
        socket_options=[(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
    ) 
Example 64
Project: splunk-for-securityHub   Author: splunk   File: args.py    MIT License 5 votes vote down vote up
def _compute_socket_options(self, scoped_config):
        # This disables Nagle's algorithm and is the default socket options
        # in urllib3.
        socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
        if scoped_config:
            # Enables TCP Keepalive if specified in shared config file.
            if self._ensure_boolean(scoped_config.get('tcp_keepalive', False)):
                socket_options.append(
                    (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1))
        return socket_options 
Example 65
Project: splunk-for-securityHub   Author: splunk   File: args.py    MIT License 5 votes vote down vote up
def _compute_socket_options(self, scoped_config):
        # This disables Nagle's algorithm and is the default socket options
        # in urllib3.
        socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
        if scoped_config:
            # Enables TCP Keepalive if specified in shared config file.
            if self._ensure_boolean(scoped_config.get('tcp_keepalive', False)):
                socket_options.append(
                    (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1))
        return socket_options 
Example 66
Project: SenseME-Indigo-Plugin   Author: bpennypacker   File: plugin.py    GNU General Public License v2.0 5 votes vote down vote up
def __connect_to_fan(self, reinit):
        if reinit == True:
            time.sleep(3)

        if self.sock == None:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            # Enable keepalive
            TCP_KEEPALIVE = 0x10
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self.sock.setsockopt(socket.IPPROTO_TCP, TCP_KEEPALIVE, 60)

        self.q.put((MSG_DEBUG, self.devID, "Thread connecting to " + self.fanIP))

        try:
            self.sock.connect((self.fanIP, 31415))
            self.tick = int(time.time())

        except socket.error as e:
            msg = "Bind to %s failed. Error %s : %s" % (self.fanIP, str(e[0]), e[1])
            self.q.put((MSG_DEBUG, self.devID, msg))
            self.sock.close()
            self.sock = None
            return

        if reinit == True:
            self.q.put((MSG_REINIT, self.devID, ""))

        self.sock.setblocking(0)

        # Send a GETALL to the newly connected fan to learn al about it
        msg = "<%s;GETALL>" % ( self.fanID )
        self.sock.send(msg)

        # GETALL apparently doesn't return the status of the motion detector, so also request
        # the motion detector status
        msg = "<%s;SNSROCC;STATUS;GET>" % ( self.fanID )
        self.sock.send(msg) 
Example 67
Project: gimel   Author: Alephbet   File: connection.py    MIT License 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 68
Project: nats-python   Author: Gr1N   File: client.py    MIT License 5 votes vote down vote up
def connect(self) -> None:
        sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)

        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        if self._socket_options["keepalive"]:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        sock.settimeout(self._socket_options["timeout"])
        sock.connect((self._conn_options["hostname"], self._conn_options["port"]))

        self._socket_file = sock.makefile("rb")
        self._socket = sock

        self._send_connect_command()
        self._recv(INFO_RE) 
Example 69
Project: weibo_twitter_earnings_analysis   Author: lynings   File: tcp.py    Apache License 2.0 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 70
Project: weibo_twitter_earnings_analysis   Author: lynings   File: tcp.py    Apache License 2.0 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 71
Project: weibo_twitter_earnings_analysis   Author: lynings   File: tcp.py    Apache License 2.0 5 votes vote down vote up
def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE)) 
Example 72
Project: weibo_twitter_earnings_analysis   Author: lynings   File: tcp.py    Apache License 2.0 5 votes vote down vote up
def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled) 
Example 73
Project: TornadoWeb   Author: VxCoder   File: connections.py    Apache License 2.0 4 votes vote down vote up
def connect(self):
        #TODO: Set close callback
        #raise OperationalError(2006, "MySQL server has gone away (%r)" % (e,))
        sock = None
        try:
            if self.unix_socket and self.host in ('localhost', '127.0.0.1'):
                sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                addr = self.unix_socket
                self.host_info = "Localhost via UNIX socket: " + self.unix_socket
            else:
                sock = socket.socket()
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                addr = (self.host, self.port)
                self.host_info = "socket %s:%d" % (self.host, self.port)
            stream = iostream.IOStream(sock)
            # TODO: handle connect_timeout
            yield stream.connect(addr)
            self._stream = stream

            if self.no_delay:
                stream.set_nodelay(True)

            yield self._get_server_information()
            yield self._request_authentication()

            self.connected_time = self.io_loop.time()

            if self.sql_mode is not None:
                yield self.query("SET sql_mode=%s" % (self.sql_mode,))

            if self.init_command is not None:
                yield self.query(self.init_command)
                yield self.commit()

            if self.autocommit_mode is not None:
                yield self.autocommit(self.autocommit_mode)
        except BaseException as e:
            if sock is not None:
                try:
                    sock.close()
                except socket.error:
                    pass
            self._stream = None
            if isinstance(e, err.MySQLError):
                raise
            raise OperationalError(
                2003, "Can't connect to MySQL server on %r (%s)" % (self.host, e)) 
Example 74
Project: recruit   Author: Frank-qlu   File: pool.py    Apache License 2.0 4 votes vote down vote up
def create_connection(self):
        """Connect and return a socket object.

        This is a modified version of create_connection from
        CPython >=2.6.
        """
        host, port = self.pair

        # Check if dealing with a unix domain socket
        if host.endswith('.sock'):
            if not hasattr(socket, "AF_UNIX"):
                raise ConnectionFailure("UNIX-sockets are not supported "
                                        "on this system")
            sock = socket.socket(socket.AF_UNIX)
            try:
                sock.connect(host)
                return sock
            except socket.error as e:
                if sock is not None:
                    sock.close()
                raise e

        # Don't try IPv6 if we don't support it. Also skip it if host
        # is 'localhost' (::1 is fine). Avoids slow connect issues
        # like PYTHON-356.
        family = socket.AF_INET
        if socket.has_ipv6 and host != 'localhost':
            family = socket.AF_UNSPEC

        err = None
        for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
            af, socktype, proto, dummy, sa = res
            sock = None
            try:
                sock = socket.socket(af, socktype, proto)
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,
                                self.socket_keepalive)
                sock.settimeout(self.conn_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:
            # This likely means we tried to connect to an IPv6 only
            # host with an OS/kernel or Python interpreter that doesn't
            # support IPv6. The test case is Jython2.5.1 which doesn't
            # support IPv6 at all.
            raise socket.error('getaddrinfo failed') 
Example 75
Project: pweby   Author: syfun   File: utils.py    Apache License 2.0 4 votes vote down vote up
def set_tcp_keepalive(sock, tcp_keepalive=True,
                      tcp_keepidle=None,
                      tcp_keepalive_interval=None,
                      tcp_keepalive_count=None):
    """Set values for tcp keepalive parameters

    This function configures tcp keepalive parameters if users wish to do
    so.

    :param tcp_keepalive: Boolean, turn on or off tcp_keepalive. If users are
      not sure, this should be True, and default values will be used.

    :param tcp_keepidle: time to wait before starting to send keepalive probes
    :param tcp_keepalive_interval: time between successive probes, once the
      initial wait time is over
    :param tcp_keepalive_count: number of probes to send before the connection
      is killed
    """

    # NOTE(praneshp): Despite keepalive being a tcp concept, the level is
    # still SOL_SOCKET. This is a quirk.
    if isinstance(tcp_keepalive, bool):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, tcp_keepalive)
    else:
        raise TypeError("tcp_keepalive must be a boolean")

    if not tcp_keepalive:
        return

    # These options aren't available in the OS X version of eventlet,
    # Idle + Count * Interval effectively gives you the total timeout.
    if tcp_keepidle is not None:
        if hasattr(socket, 'TCP_KEEPIDLE'):
            sock.setsockopt(socket.IPPROTO_TCP,
                            socket.TCP_KEEPIDLE,
                            tcp_keepidle)
        else:
            LOG.warning('tcp_keepidle not available on your system')
    if tcp_keepalive_interval is not None:
        if hasattr(socket, 'TCP_KEEPINTVL'):
            sock.setsockopt(socket.IPPROTO_TCP,
                            socket.TCP_KEEPINTVL,
                            tcp_keepalive_interval)
        else:
            LOG.warning('tcp_keepintvl not available on your system')
    if tcp_keepalive_count is not None:
        if hasattr(socket, 'TCP_KEEPCNT'):
            sock.setsockopt(socket.IPPROTO_TCP,
                            socket.TCP_KEEPCNT,
                            tcp_keepalive_count)
        else:
            LOG.warning('tcp_keepcnt not available on your system') 
Example 76
Project: VManagePlatform   Author: Moniter123   File: websocket.py    GNU General Public License v2.0 4 votes vote down vote up
def socket(host, port=None, connect=False, prefer_ipv6=False,
               unix_socket=None, use_ssl=False, tcp_keepalive=True,
               tcp_keepcnt=None, tcp_keepidle=None, tcp_keepintvl=None):
        """ Resolve a host (and optional port) to an IPv4 or IPv6
        address. Create a socket. Bind to it if listen is set,
        otherwise connect to it. Return the socket.
        """
        flags = 0
        if host == '':
            host = None
        if connect and not (port or unix_socket):
            raise Exception("Connect mode requires a port")
        if use_ssl and not ssl:
            raise Exception("SSL socket requested but Python SSL module not loaded.");
        if not connect and use_ssl:
            raise Exception("SSL only supported in connect mode (for now)")
        if not connect:
            flags = flags | socket.AI_PASSIVE

        if not unix_socket:
            addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM,
                    socket.IPPROTO_TCP, flags)
            if not addrs:
                raise Exception("Could not resolve host '%s'" % host)
            addrs.sort(key=lambda x: x[0])
            if prefer_ipv6:
                addrs.reverse()
            sock = socket.socket(addrs[0][0], addrs[0][1])

            if  tcp_keepalive:
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                if tcp_keepcnt:
                    sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT,
                                    tcp_keepcnt)
                if tcp_keepidle:
                    sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE,
                                    tcp_keepidle)
                if tcp_keepintvl:
                    sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL,
                                    tcp_keepintvl)

            if connect:
                sock.connect(addrs[0][4])
                if use_ssl:
                    sock = ssl.wrap_socket(sock)
            else:
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                sock.bind(addrs[0][4])
                sock.listen(100)
        else:
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.connect(unix_socket)

        return sock 
Example 77
Project: smsweb   Author: awangga   File: pool.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def _create_connection(address, options):
    """Given (host, port) and PoolOptions, connect and return a socket object.

    Can raise socket.error.

    This is a modified version of create_connection from CPython >= 2.6.
    """
    host, port = address

    # Check if dealing with a unix domain socket
    if host.endswith('.sock'):
        if not hasattr(socket, "AF_UNIX"):
            raise ConnectionFailure("UNIX-sockets are not supported "
                                    "on this system")
        sock = socket.socket(socket.AF_UNIX)
        try:
            sock.connect(host)
            return sock
        except socket.error:
            sock.close()
            raise

    # Don't try IPv6 if we don't support it. Also skip it if host
    # is 'localhost' (::1 is fine). Avoids slow connect issues
    # like PYTHON-356.
    family = socket.AF_INET
    if socket.has_ipv6 and host != 'localhost':
        family = socket.AF_UNSPEC

    err = None
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
        af, socktype, proto, dummy, sa = res
        sock = socket.socket(af, socktype, proto)
        try:
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            sock.settimeout(options.connect_timeout)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,
                            options.socket_keepalive)
            sock.connect(sa)
            return sock
        except socket.error as e:
            err = e
            sock.close()

    if err is not None:
        raise err
    else:
        # This likely means we tried to connect to an IPv6 only
        # host with an OS/kernel or Python interpreter that doesn't
        # support IPv6. The test case is Jython2.5.1 which doesn't
        # support IPv6 at all.
        raise socket.error('getaddrinfo failed') 
Example 78
Project: satori   Author: leancloud   File: pool.py    Apache License 2.0 4 votes vote down vote up
def _create_connection(address, options):
    """Given (host, port) and PoolOptions, connect and return a socket object.

    Can raise socket.error.

    This is a modified version of create_connection from CPython >= 2.6.
    """
    host, port = address

    # Check if dealing with a unix domain socket
    if host.endswith('.sock'):
        if not hasattr(socket, "AF_UNIX"):
            raise ConnectionFailure("UNIX-sockets are not supported "
                                    "on this system")
        sock = socket.socket(socket.AF_UNIX)
        try:
            sock.connect(host)
            return sock
        except socket.error:
            sock.close()
            raise

    # Don't try IPv6 if we don't support it. Also skip it if host
    # is 'localhost' (::1 is fine). Avoids slow connect issues
    # like PYTHON-356.
    family = socket.AF_INET
    if socket.has_ipv6 and host != 'localhost':
        family = socket.AF_UNSPEC

    err = None
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
        af, socktype, proto, dummy, sa = res
        sock = socket.socket(af, socktype, proto)
        try:
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            sock.settimeout(options.connect_timeout)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,
                            options.socket_keepalive)
            sock.connect(sa)
            return sock
        except socket.error as e:
            err = e
            sock.close()

    if err is not None:
        raise err
    else:
        # This likely means we tried to connect to an IPv6 only
        # host with an OS/kernel or Python interpreter that doesn't
        # support IPv6. The test case is Jython2.5.1 which doesn't
        # support IPv6 at all.
        raise socket.error('getaddrinfo failed') 
Example 79
Project: mikrotik-arpwatch   Author: davidnutter   File: mikrotik-arpwatch.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def establish_session():
    "Create a session with the routerboard API. Failures are logged. Socket is returned or Exceptions raised in the case of failure"
    hostbits = global_options.api_host.split(":")
    if len(hostbits) == 1:
        host = hostbits[0]
        port = int(DEFAULT_PORT)
    elif len(hostbits) ==2:
        host = hostbits[0]
        port = int(hostbits[1])
    else:
        ArpWatchLogging.log_message(syslog.LOG_ERR,"Host spec %s does not appear to be in host.name:port format. Aborting" % global_options.host)
        sys.exit(1)
    

    addr = socket.gethostbyname(host)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    if global_options.api_keepalive_enabled:
       x = s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)
       if (x == 0):              
          x = s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
          s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, global_options.api_keepalive_time)
          s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, global_options.api_keepalive_probes)
          s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, global_options.api_keepalive_interval)
          
          ArpWatchLogging.log_message(syslog.LOG_NOTICE,"TCP Keepalive enabled: time=%d, probes=%d, probe_interval=%d" %
                                      (global_options.api_keepalive_time,
                                       global_options.api_keepalive_probes,
                                       global_options.api_keepalive_interval))
    else:
       ArpWatchLogging.log_message(syslog.LOG_WARNING,
                                   "TCP keepalive is disabled. Network disruption may cause this daemon to silently lose communication with the routerboard. Consider a periodic restart via cron to work around this potential issue")
                                       

    #TODO: Potentially set an explicit timeout here so we don't hang around for too long connecting to an unresponsive host
    ArpWatchLogging.log_message(syslog.LOG_NOTICE, "Attempting connection to routerboard %s" % global_options.api_host)
    s.connect((addr, port))  
    ArpWatchLogging.log_message(syslog.LOG_NOTICE, "Connected to routerboard %s" % global_options.api_host)
                                
    apiros = RosAPI.ApiRos(s)
    (login_ok,message)=apiros.login(global_options.api_user,global_options.api_password)

    if not login_ok:
       err_message="Login to routerboard failed. Potential Username/password issue.\nRouterboard responded: '%s' " % message
       ArpWatchLogging.log_message(syslog.LOG_ERR, err_message)
       s.close()
       raise LoginError(err_message)

    return apiros 
Example 80
Project: visonic   Author: davesmeghead   File: pyvisonic.py    Apache License 2.0 4 votes vote down vote up
def create_tcp_visonic_connection(address, port, protocol=VisonicProtocol, command_queue = None, event_callback=None, disconnect_callback=None, loop=None):
    """Create Visonic manager class, returns tcp transport coroutine."""

    # use default protocol if not specified
    protocol = partial(
        protocol,
        loop=loop if loop else asyncio.get_event_loop(),
        event_callback=event_callback,
        disconnect_callback=disconnect_callback,
        command_queue = command_queue, 
#        ignore=ignore if ignore else [],
    )

    address = address
    port = port
    
    sock = None
    try:
        log.info("Setting TCP socket Options")
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt( socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        sock.setblocking(1)      # Set blocking to on, this is the default but just make sure
        sock.settimeout( 1.0 )   # set timeout to 1 second to flush the receive buffer
        sock.connect((address, port))
        
        # Flush the buffer, receive any data and dump it
        try:
            rec = sock.recv(10000) # try to receive 100 bytes
            log.info("Buffer Flushed and Received some data!")
        except socket.timeout: # fail after 1 second of no activity
            log.info("Buffer Flushed and Didn't receive data! [Timeout]")
    
        # set the timeout to infinite
        sock.settimeout( None ) 
        
        conn = loop.create_connection(protocol, sock=sock)
        return conn
    except socket.error as _:
        err = _
        log.info("Setting TCP socket Options Exception {0}".format(err))
        if sock is not None:
            sock.close()
    return None


# Create a connection using asyncio through a linux port (usb or rs232)