Fetching the Server IP Address with Python Requests

Feb 3, 2024 ยท 2 min read

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 Response.raw socket connection:

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 X-Served-By header often contains the server's IP.

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.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!