Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get the IP address of the URL in requests module in Python 3.5.1

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.

like image 430
Swadeep Avatar asked Dec 06 '25 14:12

Swadeep


1 Answers

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())
like image 179
Martijn Pieters Avatar answered Dec 08 '25 04:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!