3

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.

1 Answer 1

7

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())
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.