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:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: