user321627
user321627

Reputation: 2564

In Python, for a POST request, is it possible to obtain the ip address used for the request from the POST request object?

For a general POST request in Python like:

>>> import requests
>>> r = requests.post(url=url, data=data, headers = headers, cookies = cookies)
>>> type(r)
<class 'requests.models.Response'>

Is it possible to obtain the ip address that was used at the time the post request was made? I have tried to look through its contents using dir(r) and got:

dir(r)

['attrs', 'bool', 'class', 'delattr', 'dict', 'dir', 'doc', 'enter', 'eq', 'exit', 'format', 'ge', 'getattribute', 'getstate', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'lt', 'module', 'ne', 'new', 'nonzero', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'weakref', '_content', '_content_consumed', '_next', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'next', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']

Is there something in here that might contain it? thanks.

Upvotes: 1

Views: 727

Answers (1)

user2864740
user2864740

Reputation: 61875

"No". The actual IP resolution happens relatively low in the HTTP request stack and is generally not exposed (in 'any' higher-level HTTP API, regardless of language implementation).

Instead, get the hostname from the url and resolve the extracted hostname to an IP.

There is a very brief timing window that technically 'could' result in a different value, but it "ought to be good enough" - especially since the network name resolution is cached, and putting that much reliance on a resolved IP sounds .. funky.

(While one could resolve the IP first, and use that for the request, it would also change the HTTP host headers. So: probably not useful.)

Upvotes: 1

Related Questions