0

While using python-requests, I want to print the IP address I use for each request regardless if it is the same static IP or if I'm rotating it, so my question is, is there a method in the requests module or a snippet of code that does this job?

wait3
  • 45
  • 6
  • see https://stackoverflow.com/questions/22492484/how-do-i-get-the-ip-address-from-a-http-request-using-the-requests-library – balderman Sep 15 '21 at 11:12

1 Answers1

0

I find this on another answer but it should works in python:

from requests.packages.urllib3.connectionpool import HTTPConnectionPool

def _make_request(self,conn,method,url,**kwargs):
    response = self._old_make_request(conn,method,url,**kwargs)
    sock = getattr(conn,'sock',False)
    if sock:
        setattr(response,'peer',sock.getpeername())
    else:
        setattr(response,'peer',None)
    return response

HTTPConnectionPool._old_make_request = HTTPConnectionPool._make_request
HTTPConnectionPool._make_request = _make_request

import requests

r = requests.get('http://www.google.com')
print(r.raw._original_response.peer)

results:

('142.250.184.36', 80)