When making HTTP requests in Python using the Requests module, you may find it useful to get the IP address of the server you are connecting to. Here are a few ways to fetch and print the server IP with Requests.
First, make a simple GET request:
import requests
response = requests.get('https://www.example.com')
The server IP can then be accessed via the
print(response.raw._connection.sock.getpeername()[0])
This prints the remote server's IP address that your request connected to.
Another way is to get the resolved IP from the request URL:
print(response.url.split("/")[2])
This splits up the URL and prints out the domain/IP section.
Alternatively, you can get the server IP from the response headers:
print(response.headers['X-Served-By'])
The
Beware that proxies, CDNs, or load balancers may mean you get an intermediate IP rather than the origin server.
To validate the server IP, you can do a reverse DNS lookup:
import socket
print(socket.gethostbyaddr(server_ip)[0])
This prints out the hostname mapping to that IP.
Checking the server IP can be useful for monitoring, security, analytics, and troubleshooting purposes. For example, maintaining a whitelist of known server IPs, or comparing the IP against a known source to check for proxies.
Hopefully this gives you some ideas on how to fetch and validate server IPs with Python Requests.