【问题标题】:How to Get the IP address of the URL in requests module in Python 3.5.1如何在 Python 3.5.1 的 requests 模块中获取 URL 的 IP 地址
【发布时间】:2026-01-07 01:30:01
【问题描述】:

Python 版本:3.5.1

请求版本:2.9.1。

我正在尝试获取 python 请求中 url 的 IP 地址,如下所述:How do I get the IP address from a http request using the requests library?

import requests
rsp = requests.get('http://google.com', stream=True)
# grab the IP while you can, before you consume the body!!!!!!!!
print (rsp.raw._fp.fp._sock.getpeername())
# consume the body, which calls the read(), after that fileno is no longer available.
print (rsp.content)

出现以下错误:

AttributeError: '_io.BufferedReader' object has no attribute '_sock'

可能是一些版本问题。请帮忙。

附:无法在原始帖子中发表评论。

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    你到了BufferedReader instance;它是添加缓冲区的实际文件对象的包装器。原始文件对象可通过raw attribute

    print(rsp.raw._fp.fp.raw._sock.getpeername())
    

    演示:

    >>> import requests
    >>> rsp = requests.get('http://google.com', stream=True)
    >>> print(rsp.raw._fp.fp.raw._sock.getpeername())
    ('2a00:1450:400b:c02::69', 80, 0, 0)
    

    要使代码同时在 Python 2 和 3 上运行,请查看 raw 属性是否存在:

    fp = rsp.raw._fp.fp
    sock = fp.raw._sock if hasattr(fp, 'raw') else fp._sock
    print(sock.getpeername())
    

    【讨论】: