As the title says, if I do resp=httpx.get(url)
how do I get the IP from which the url
was resolved?
There's This question about how to do it with requests
but the same methods don't appear to exist in the httpx
objects.
Empirically, you can do it with an exquisitely ugly incantation like as follows.
Do note that this involves digging into no less than 6 underscore-private attribute of the response stream, so it could stop working at any time when you upgrade httpx
. (This worked for me with httpx 0.23.0.)
import httpx
with httpx.Client() as hc:
r = hc.get("https://httpbin.org/get")
peername = r.stream._stream._httpcore_stream._stream._connection._network_stream._sock.getpeername()
print(r.json())
print(peername)
This prints out
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-httpx/0.23.0', 'X-Amzn-Trace-Id': 'Root=...'}, 'origin': '....', 'url': 'https://httpbin.org/get'}
('44.207.168.240', 443)