Check your public IP address using python

If you ever need to quickly check your public IP address, one efficient way to do it is by calling an IP search website. Below is a short snippet of Python code that demonstrates how to achieve this using the requests library.

import requests

url = ""


# output

How It Works:

The script sends an HTTP GET request to The response is a JSON object that contains your public IP address.

Why This Works:

When your request reaches the server (in this case,, it carries with it metadata including the public IP address from which it originated. This public IP is visible to the server because it’s used to route data back to your machine.

Here’s a simplified explanation of how it all works:

  1. Request Sent: When you make a request to the server, it travels through the Internet. Your request packet contains your public IP address as part of its metadata.
  2. Server Reception: On reaching the server (, this public IP is captured by the server-side application.
  3. Response Generation: The server constructs a JSON response containing this IP address.
  4. Sending Back: The server sends this JSON response back to your machine.

This entire process leverages the fundamental way the internet routes traffic between clients (like your computer) and servers.

By simply using an HTTP client like requests, you effectively ask the server what public IP it sees you coming from, hence obtaining your public IP address.

This method is quick and provides accurate results, making it a handy tool for checking your public IP address programmatically.

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !