Python Version : 3.5.1
requests version: 2.9.1.
I am trying to get the IP address of url in python's request like below as explained here: 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)
Getting below error:
AttributeError: '_io.BufferedReader' object has no attribute '_sock'
May be some version issues. Please help.
P.S. Unable to comment in original post.
You got to the BufferedReader instance; it is a wrapper around the actual file object adding a buffer. The original file object is reachable via the raw attribute:
print(rsp.raw._fp.fp.raw._sock.getpeername())
Demo:
>>> 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)
To make the code work on both Python 2 and 3, see if the raw attribute is there:
fp = rsp.raw._fp.fp
sock = fp.raw._sock if hasattr(fp, 'raw') else fp._sock
print(sock.getpeername())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With