简体   繁体   中英

Python Requests - Get Server IP

I'm making a small tool that tests CDN performance and would like to check where the response comes from. I thought of getting the host's IP and then using one of the geolocation API's on github to check the country.

I've tried doing so with

import socket
...
raw._fp.fp._sock.getpeername()

...however that only works when i use stream=True for the request and that in turn breaks the tool's functionality. Is there any other option to get the server ip with requests or in a completely different way?

The socket.gethostbyname() function from Python's socket library should solve your problem. You can check it out in the Python docs here .

Here is an example of how to use it:

import socket
url="cdnjs.cloudflare.com"
print("IP:",socket.gethostbyname(url))

All you need to do is pass the url to socket.gethostbyname() and it will do the rest. Just make sure to remove the http:// before the URL because that will trip it up.

I could not get Akilan's solution to give the IP address of a different host that I was using. socket.gethostbyname() and getpeername() were not working for me. They are not even available. His solution did open the door.

However, navigating the socket object, I did find this:

socket.getaddrinfo('host name', 443)[0][4][0]

I wrapped this in a try/except block.

Maybe there is a prettier way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM