Python socket._socketobject() Examples

The following are code examples for showing how to use socket._socketobject(). 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: socks5man   Author: RicoVZ   File: helpers.py    GNU General Public License v3.0 7 votes vote down vote up
def get_over_socks5(url, host, port, username=None, password=None, timeout=3):
    """Make a HTTP GET request over socks5 of the given URL"""
    socks.set_default_proxy(
        socks.SOCKS5, host, port,
        username=username, password=password
    )

    response = None
    try:
        socket.socket = socks.socksocket
        response = urllib2.urlopen(url, timeout=timeout).read()
    except (socket.error, urllib2.URLError, socks.ProxyError) as e:
        log.error("Error making HTTP GET over socks5: %s", e)
    finally:
        socket.socket = socket._socketobject
    return response 
Example 2
Project: pyblish-win   Author: pyblish   File: test_urllib2net.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.example.com/")
        abused_fileobject = response.fp
        self.assertIs(abused_fileobject.__class__, socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertIs(fileobject.__class__, socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example 3
Project: ironpython2   Author: IronLanguages   File: test_urllib2net.py    Apache License 2.0 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.example.com/")
        abused_fileobject = response.fp
        self.assertIs(abused_fileobject.__class__, socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertIs(fileobject.__class__, socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example 4
Project: open-recipe   Author: dspray95   File: tcp.py    The Unlicense 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is L{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example 5
Project: oss-ftp   Author: aliyun   File: test_urllib2net.py    MIT License 6 votes vote down vote up
def test_close(self):
        import httplib

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = _urlopen_with_retry("http://www.example.com/")
        abused_fileobject = response.fp
        self.assertIs(abused_fileobject.__class__, socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assertIs(fileobject.__class__, socket._fileobject)

        self.assertTrue(not fileobject.closed)
        response.close()
        self.assertTrue(fileobject.closed) 
Example 6
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    GNU General Public License v2.0 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is L{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example 7
Project: py-zabbix   Author: adubkov   File: sender.py    GNU General Public License v2.0 6 votes vote down vote up
def _receive(self, sock, count):
        """Reads socket to receive data from zabbix server.

        :type socket: :class:`socket._socketobject`
        :param socket: Socket to read.

        :type count: int
        :param count: Number of bytes to read from socket.
        """

        buf = b''

        while len(buf) < count:
            chunk = sock.recv(count - len(buf))
            if not chunk:
                break
            buf += chunk

        return buf 
Example 8
Project: btcnano-wallet-client-desktop   Author: bitcoinnano   File: network.py    MIT License 6 votes vote down vote up
def set_proxy(self, proxy):
        self.proxy = proxy
        # Store these somewhere so we can un-monkey-patch
        if not hasattr(socket, "_socketobject"):
            socket._socketobject = socket.socket
            socket._getaddrinfo = socket.getaddrinfo
        if proxy:
            self.print_error('setting proxy', proxy)
            proxy_mode = proxy_modes.index(proxy["mode"]) + 1
            socks.setdefaultproxy(proxy_mode,
                                  proxy["host"],
                                  int(proxy["port"]),
                                  # socks.py seems to want either None or a non-empty string
                                  username=(proxy.get("user", "") or None),
                                  password=(proxy.get("password", "") or None))
            socket.socket = socks.socksocket
            # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
            socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
        else:
            socket.socket = socket._socketobject
            socket.getaddrinfo = socket._getaddrinfo 
Example 9
Project: weibo_twitter_earnings_analysis   Author: lynings   File: tcp.py    Apache License 2.0 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is L{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example 10
Project: pylgbst   Author: undera   File: __init__.py    MIT License 6 votes vote down vote up
def _handle_conn(self, conn):
        """
        :type conn: socket._socketobject
        """
        buf = ""
        while True:
            data = conn.recv(1024)
            log.debug("Recv: %s", data.strip())
            if not data:
                break

            buf += data

            if "\n" in buf:
                line = buf[:buf.index("\n")]
                buf = buf[buf.index("\n") + 1:]

                if line:
                    log.debug("Cmd line: %s", line)
                    try:
                        self._handle_cmd(json.loads(line))
                    except KeyboardInterrupt:
                        raise
                    except BaseException:
                        log.error("Failed to handle cmd: %s", traceback.format_exc()) 
Example 11
Project: learn_python3_spider   Author: wistbean   File: tcp.py    MIT License 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is L{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example 12
Project: Hot   Author: dsolimando   File: test_urllib2net.py    GNU General Public License v3.0 6 votes vote down vote up
def test_close(self):
        import socket, httplib, gc

        # calling .close() on urllib2's response objects should close the
        # underlying socket

        # delve deep into response to fetch socket._socketobject
        response = urllib2.urlopen("http://www.python.org/")
        abused_fileobject = response.fp
        self.assert_(abused_fileobject.__class__ is socket._fileobject)
        httpresponse = abused_fileobject._sock
        self.assert_(httpresponse.__class__ is httplib.HTTPResponse)
        fileobject = httpresponse.fp
        self.assert_(fileobject.__class__ is socket._fileobject)

        self.assert_(not fileobject.closed)
        response.close()
        self.assert_(fileobject.closed) 
Example 13
Project: CraftProtocol   Author: Toranktto   File: StreamIO.py    MIT License 6 votes vote down vote up
def read(stream, n):
        if isinstance(stream, socket._socketobject):
            data = stream.recv(n)
            while len(data) < n:
                packet = stream.recv(n - len(data))
                if not packet:
                    stream.close()
                    raise EOFError("Unexpected EOF while reading bytes")

                data += packet

            return data

        data = stream.read(n)
        if len(data) < n:
            raise EOFError("Unexpected EOF while reading bytes")

        return data 
Example 14
Project: server   Author: lowitty   File: tcp.py    MIT License 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is C{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example 15
Project: server   Author: lowitty   File: tcp.py    MIT License 6 votes vote down vote up
def _finishInit(self, whenDone, skt, error, reactor):
        """
        Called by subclasses to continue to the stage of initialization where
        the socket connect attempt is made.

        @param whenDone: A 0-argument callable to invoke once the connection is
            set up.  This is C{None} if the connection could not be prepared
            due to a previous error.

        @param skt: The socket object to use to perform the connection.
        @type skt: C{socket._socketobject}

        @param error: The error to fail the connection with.

        @param reactor: The reactor to use for this client.
        @type reactor: L{twisted.internet.interfaces.IReactorTime}
        """
        if whenDone:
            self._commonConnection.__init__(self, skt, None, reactor)
            reactor.callLater(0, whenDone)
        else:
            reactor.callLater(0, self.failIfNotConnected, error) 
Example 16
Project: tacacs_plus   Author: ansible   File: test_tacacs_plus.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fake_socket(tmpdir_factory, request):
    packets = request.node.callspec.params.get('packets')

    # write data to the "socket"; this must be an actual file, because
    # select.select()() expects a real file descriptor
    filename = str(tmpdir_factory.mktemp('fake-socket').join(str(uuid4())))
    f = open(filename, 'w')
    request.addfinalizer(f.close)

    sockobj = socket._socket.socket if six.PY3 else socket._socketobject

    class fakesocket(sockobj):
        buff = six.BytesIO()

    def _send(self, data):
        self.buff.write(data)
        return len(data)  # number of bytes sent

    sock = fakesocket()
    sock.f = six.BytesIO(packets)
    # socket.socket overrides these at instantiation time to the underlying
    # C implementation; set them here so that we can mock send() and recv()
    # calls
    sock.send = types.MethodType(_send, sock)
    sock.recv = types.MethodType(
        lambda self, _bytes: self.f.read(_bytes),
        sock
    )
    sock.fileno = types.MethodType(lambda self: f.fileno(), sock)
    return sock 
Example 17
Project: py-zabbix   Author: adubkov   File: sender.py    GNU General Public License v2.0 5 votes vote down vote up
def _get_response(self, connection):
        """Get response from zabbix server, reads from self.socket.

        :type connection: :class:`socket._socketobject`
        :param connection: Socket to read.

        :rtype: dict
        :return: Response from zabbix server or False in case of error.
        """

        response_header = self._receive(connection, 13)
        logger.debug('Response header: %s', response_header)

        if (not response_header.startswith(b'ZBXD\x01') or
                len(response_header) != 13):
            logger.debug('Zabbix return not valid response.')
            result = False
        else:
            response_len = struct.unpack('<Q', response_header[5:])[0]
            response_body = connection.recv(response_len)
            result = json.loads(response_body.decode("utf-8"))
            logger.debug('Data received: %s', result)

        try:
            connection.close()
        except Exception as err:
            pass

        return result 
Example 18
Project: miniworld_core   Author: miniworld-project   File: NetUtil.py    MIT License 5 votes vote down vote up
def read_remaining_data(sock, buf_size=4096):
    """
    Get the remaining (unread) data from the socket.

    Parameters
    ----------
    sock : socket._socketobject
    buf_size : int

    Returns
    -------
    str
        The data.
    """
    data = ""
    try:
        old_timeout = sock.gettimeout()
        sock.setblocking(0)
        while True:
            data += sock.recv(buf_size)
    except socket.error as e:
        # error: [Errno 11] Resource temporarily unavailable
        if not e[0] == errno.EDEADLK:
            raise e
    finally:
        # reset old timeout and (non)blocking mode
        sock.settimeout(old_timeout)
        return data 
Example 19
Project: pywincffi   Author: opalmer   File: functions.py    MIT License 5 votes vote down vote up
def socket_from_object(sock):
    """
    Converts a Python socket to a Windows SOCKET object.

    .. warning::

        This function is mainly intended for internal use.  Passing in an
        invalid object may result in a crash.

    :param socket._socketobject sock:
        The Python socket to convert to :class:`pywincffi.wintypes.SOCKET`
        object.

    :rtype: :class:`pywincffi.wintypes.SOCKET`
    """
    try:
        fileno = sock.fileno()

        # In later versions of Python calling fileno() on a closed
        # socket returns -1 instead of raising socket.error.
        if fileno == -1:
            raise socket.error(socket.errno.EBADF, "Bad file descriptor")

    except AttributeError:
        raise InputError(
            "sock", sock,
            message="Expected a Python socket object for `sock`")
    except socket.error as error:
        raise InputError(
            "sock", sock,
            message="Invalid socket object (error: %s)" % error)
    else:
        ffi, _ = dist.load()
        sock = SOCKET()
        sock._cdata[0] = ffi.cast("SOCKET", fileno)
        return sock 
Example 20
Project: btcnano-wallet-client-desktop   Author: bitcoinnano   File: network_dialog.py    MIT License 5 votes vote down vote up
def is_tor_port(port):
        try:
            s = (socket._socketobject if hasattr(socket, "_socketobject") else socket.socket)(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(0.1)
            s.connect(("127.0.0.1", port))
            # Tor responds uniquely to HTTP-like requests
            s.send(b"GET\n")
            if b"Tor is not an HTTP Proxy" in s.recv(1024):
                return True
        except socket.error:
            pass
        return False 
Example 21
Project: dpm-py   Author: openknowledge-archive   File: mock_socket.py    MIT License 5 votes vote down vote up
def patch_socket():
    socket.socket = MockSocket
    socket.socket = socket.__dict__['socket'] = MockSocket
    socket._socketobject = socket.__dict__['_socketobject'] = MockSocket
    socket.SocketType = socket.__dict__['SocketType'] = MockSocket
    socket.create_connection = socket.__dict__['create_connection'] = create_connection
    socket.getaddrinfo = socket.__dict__['getaddrinfo'] = getaddrinfo
    socket.gethostname = socket.__dict__['gethostname'] = lambda: 'localhost'
    socket.gethostbyname = socket.__dict__['gethostbyname'] = lambda host: '127.0.0.1'
    socket.inet_aton = socket.__dict__['inet_aton'] = lambda host: '127.0.0.1' 
Example 22
Project: CraftProtocol   Author: Toranktto   File: StreamIO.py    MIT License 5 votes vote down vote up
def write(stream, data):
        if isinstance(stream, socket._socketobject):
            return stream.send(data)

        return stream.write(data) 
Example 23
Project: encompass   Author: martexcoin   File: network.py    GNU General Public License v3.0 5 votes vote down vote up
def set_proxy(self, proxy):
        self.proxy = proxy
        if proxy:
            proxy_mode = proxy_modes.index(proxy["mode"]) + 1
            socks.setdefaultproxy(proxy_mode, proxy["host"], int(proxy["port"]))
            socket.socket = socks.socksocket
            # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
            socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
        else:
            socket.socket = socket._socketobject
            socket.getaddrinfo = socket._socket.getaddrinfo