Last modified: Sep 13, 2026

Python Get IP Address

Getting the IP address in Python is a common task for developers working with network applications. Whether you want to find your local IP address or your public IP address, Python provides several methods to accomplish this. This article will walk you through different ways to retrieve IP addresses using built-in modules and external libraries. You will also see example code and output for each method.

Local IP Address Using Socket

The socket module is part of Python’s standard library. It allows you to interact with the network at a low level. You can use it to get the local IP address of the machine.

Here is a simple example. The script connects to an external server without sending data. This forces the socket to resolve the local IP address used for the connection.


import socket

def get_local_ip():
    # Create a UDP socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # Connect to an external address
        s.connect(("8.8.8.8", 80))
        # Get the local IP address
        ip = s.getsockname()[0]
    except Exception as e:
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip

print("Local IP Address:", get_local_ip())

Local IP Address: 192.168.1.5

This method works on most systems. It does not require any external packages. It is fast and reliable for local network tasks.

Public IP Address Using Requests

To get the public IP address, you need to contact an external service. The requests library makes this easy. It sends an HTTP request to a web API that returns your public IP.

First, install the requests library if you do not have it.


pip install requests

Now use the following code to fetch your public IP address.


import requests

def get_public_ip():
    # Send a request to the ipify API
    response = requests.get("https://api.ipify.org?format=json")
    # Parse the JSON response
    ip = response.json()["ip"]
    return ip

print("Public IP Address:", get_public_ip())

Public IP Address: 203.0.113.45

The API returns a JSON object with your public IP. You can use other services like ifconfig.me or ipecho.net as well.

Get All IP Addresses Using Netifaces

If you need to list all network interfaces and their IP addresses, use the netifaces library. It provides a cross-platform way to access network configuration.

Install it using pip.


pip install netifaces

Here is how you can list all IP addresses.


import netifaces

def get_all_ips():
    # Get a list of all interfaces
    interfaces = netifaces.interfaces()
    for interface in interfaces:
        print(f"Interface: {interface}")
        # Get addresses for each interface
        addresses = netifaces.ifaddresses(interface)
        # Filter for IPv4 addresses
        if netifaces.AF_INET in addresses:
            for addr_info in addresses[netifaces.AF_INET]:
                print(f"  IPv4 Address: {addr_info['addr']}")

get_all_ips()

Interface: lo
  IPv4 Address: 127.0.0.1
Interface: eth0
  IPv4 Address: 192.168.1.5
Interface: wlan0
  IPv4 Address: 192.168.0.10

This is useful for applications that need to bind to specific interfaces or scan all available IPs.

Using Hostname to Find IP

You can also get the IP address associated with a hostname using the gethostbyname method. This is helpful when you need to resolve domain names.


import socket

def get_ip_from_hostname(hostname):
    # Resolve hostname to IP address
    ip = socket.gethostbyname(hostname)
    return ip

print("IP for google.com:", get_ip_from_hostname("google.com"))

IP for google.com: 142.250.191.14

This method resolves the hostname to its primary IP address. It is part of the socket module and works out of the box.

Error Handling Tips

When working with network operations, always handle exceptions. Network calls can fail due to connectivity issues or invalid input. Wrap your code in try-except blocks.


import requests

def safe_get_public_ip():
    try:
        # Attempt to fetch public IP
        response = requests.get("https://api.ipify.org?format=json", timeout=5)
        response.raise_for_status()
        return response.json()["ip"]
    except requests.RequestException as e:
        # Handle any request-related errors
        print("Error fetching IP:", e)
        return None

print("Public IP:", safe_get_public_ip())

Public IP: 203.0.113.45

Using a timeout prevents your program from hanging indefinitely. Always validate responses before parsing them.

Conclusion

Retrieving IP addresses in Python is straightforward once you know which tools to use. For local IPs, the socket module is efficient and built-in. For public IPs, use requests with a web API. For advanced interface details, netifaces is the best choice. Always include error handling to make your code robust. With these examples, you can now confidently get IP addresses in your Python projects.