Guides
Last Updated Dec 07, 2023

How to Find Your IP Address Using Python

Nick Johnson

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Introduction to IP Addresses in Python

This tutorial is an introduction to finding your IPV4 or IPV6 address using Python.  IP (Internet Protocol) addresses are integral to network communication, and Python provides built-in libraries to simplify their retrieval. This section will introduce the concept of IP addresses and their importance in Python networking while providing code examples and syntax for use.

Prerequisites for IP Address Retrieval

Before diving into the Python code, you’ll need to have a few things in place. First, ensure you have Python 3.x installed. It comes with the socket module, a standard feature for network communication, so no additional installation is needed for it.

However, you’ll also need the requests library, specifically version 2.x.x or higher, which isn't included in the standard Python package. To install this library, run the following on the command line.


pip install "requests>=2.*"

This command will install the latest available version of the requests library that is version 2 or above.

For a system with multiple network interfaces, you will need to install Python’s netifaces module.


pip install netifaces

You can install Python 3 at http://www.python.org/downloads or install it via your OS package manager if available.

Let’s send your first free
API
IP Geolocation API
call
See why the best developers build on Abstract
Get your free api

Method 1: Using the Sockets Module for Internal IPv4 and IPv6 address Retrieval

Retrieve your system's internal IPv4 or IPv6 address using the socket.gethostbyname method, a straightforward solution for local hostname resolution compatible with Windows, Mac, and Linux systems.

IPv4:


import socket

try:
    hostname = socket.gethostname()
    ipv4_address = socket.gethostbyname(hostname)
    print(f"Internal IPv4 Address for {hostname}: {ipv4_address}")
except socket.gaierror:
    print("There was an error resolving the hostname.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

  1. import socket: This line imports the socket module, providing access to the BSD socket interface for various network functions.
  2. hostname = socket.gethostname(): Here, gethostname() retrieves the current machine's hostname, a label assigned to the device on a local network for identification purposes.
  3. ipv4_address = socket.gethostbyname(hostname): The gethostbyname() function translates the retrieved hostname into its corresponding IPv4 address, which is the internal address used by the device on the local network.
  4. try...except blocks: These blocks add error handling to the script. The try block encompasses the operations that might fail, such as hostname resolution. The except blocks catch and handle specific errors. socket.gaierror is caught if there's an issue with address resolution, and a general exception is caught for any other unexpected issues.
  5. print(f"IPv4 Address for {hostname}: {ipv4_address}"): This line prints the hostname and its resolved IPv4 address. The output is helpful for identifying the internal IP address through which the computer communicates over IPv4-based networks.

This method retrieves the internal network device IP only.  It is useful for diagnosing and resolving local network issues, which is critical in a variety of settings, from advanced smart home systems to complex corporate networks. For developers, this approach is invaluable for testing network applications within a LAN, ensuring smooth communication among devices.

IPv6:

IPv6 addresses can be retrieved using the socket.AF_INET6 family within the socket module. This example demonstrates how to obtain an IPv6 address:


import socket

try:
    hostname = socket.gethostname()
    ipv6_address = socket.getaddrinfo(hostname, None, socket.AF_INET6)
    print(f"IPv6 Address: {ipv6_address[0][4][0]}")
except socket.gaierror:
    print("There was an error resolving the hostname for IPv6.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
  1. import socket: Imports the socket module, used for network communications, as in the IPv4 version.
  2. hostname = socket.gethostname(): Retrieves the current machine's hostname, a label for device identification on the network.
  3. ipv6_address = socket.getaddrinfo(hostname, None, socket.AF_INET6): Fetches the IPv6 address for the hostname. The getaddrinfo function returns IPv6 address details, indicated by socket.AF_INET6.
  4. try...except blocks: Error handling is added to manage issues during hostname resolution or IPv6 fetching. The try block executes the address retrieval, and the except blocks catch specific errors, including general exceptions for robustness.
  5. print(f"IPv6 Address: {ipv6_address[0][4][0]}"): Prints the retrieved IPv6 address, located in the first tuple of the getaddrinfo result.

Method 2: Using the Requests Module for External IPv4 IP Retrieval

To determine your public IP address, you can exclusively use Python's requests module. This method is straightforward and solely focused on obtaining your public IP address, using an external service like the ipify API.


import requests

try:
    public_ip = requests.get('https://api.ipify.org').text
    print(f"Public IP Address: {public_ip}")
except requests.RequestException as e:
    print(f"Error retrieving public IP address: {e}")

This snippet demonstrates how to obtain your true public IP address using Python's requests library and the ipify API:

  1. import requests: This line imports the requests library, essential for making HTTP requests in Python. Install it using pip install requests.
  2. public_ip = requests.get('https://api.ipify.org').text: Here, a GET request is made to ipify API (https://api.ipify.org), known for its reliable service in providing external IP addresses. The .text attribute is used to extract the public IP from the response.
  3. print(f"Public IP Address: {public_ip}"): This line prints the retrieved public IP address, with Python’s f-string formatting for clearer output.
  4. Error Handling: The script includes error handling to manage potential issues like network connectivity problems or service unavailability.

In network management and IT, the ability to retrieve a public IP address is crucial. This method facilitates remote system monitoring, dynamic DNS services, and cybersecurity efforts where identifying a system's public IP is essential for tracking network activities and addressing security concerns.

Method 3: Using an API (AbstractAPI.com)

For a more comprehensive understanding of an IP address, including its geographical location, ISP, and timezone, consider using Abstract API's IP Geolocation service. This method requires obtaining a free API key from Abstract API, which then enables access to a wealth of detailed information about any given IP address. Register and get your IP Geolocation API key.


import requests

try:
    response = requests.get('https://api.abstractapi.com/v1/ipaddress/?api_key=')
    response.raise_for_status()
    ip_info = response.json()
    print(ip_info)
except requests.RequestException as e:
    print(f"An error occurred: {e}")
  1. import requests: This line imports the requests module, a Python library used for sending HTTP requests. It's essential for interacting with web APIs like AbstractAPI, allowing you to send and receive data over the internet.
  2. response = requests.get('https://api.abstractapi.com/v1/ipaddress/?api_key=YOUR_API_KEY'): Here, a GET request is sent to AbstractAPI's IP Geolocation service. The URL includes your unique API key (replace <YOUR_API_KEY> with your actual key). This request fetches detailed information about your IP address, including geographical location, ISP, and timezone.
  3. You can sign up for your free API key at AbstractAPI’s website.
  4. ip_info = response.json(): Once the request is made, the API responds with data in JSON format. This line uses the .json() method to parse the JSON response into a Python dictionary. It allows for more convenient access and manipulation of the data, such as extracting specific details about the IP address.
  5. print(ip_info): This line prints the entire response dictionary to the console. It provides a comprehensive view of the data returned by the API, including location data, ISP information, timezone, and more. It's a useful way to quickly verify the data retrieved from AbstractAPI.
  6. Error Handling: Error handling is implemented to manage potential issues during the API request. The try...except block catches exceptions related to HTTP errors, connection problems, timeouts, etc., ensuring the script can gracefully handle and report any errors."

Handling Multiple Network Interfaces in Python with Netifaces

In environments with multiple network interfaces, such as servers or complex network setups, it's often necessary to identify the IP address of each specific interface. Python's netifaces library offers an efficient solution for this task, allowing you to enumerate and interact with various network interfaces on your system. This method is particularly useful for applications that require knowledge of the network configuration, including interface-specific IP addresses.

First we want to list our network interfaces:


import netifaces

interfaces = netifaces.interfaces()

print("Available network interfaces:", interfaces)
  1. import netifaces:  This line imports the netifaces module into your Python program.
  2. interfaces = netifaces.interfaces(): Here, we're using netifaces.interfaces() to retrieve a list of all network interfaces available on the system. This function returns a list of interface names, making it easy to iterate over or select a specific network interface for further operations.
  3. print("Available network interfaces:", interfaces): This line prints out the list of network interfaces obtained in the previous step.

After you have a list of network interfaces we can use the following script to retrieve the device’s IP address:


import netifaces

def get_ip_address(interface):
    try:
        addrs = netifaces.ifaddresses(interface)
        ip_info = {}
        if netifaces.AF_INET in addrs:  # Check for IPv4 address
            ip_info['IPv4'] = addrs[netifaces.AF_INET][0]['addr']
        if netifaces.AF_INET6 in addrs:  # Check for IPv6 address
            ip_info['IPv6'] = addrs[netifaces.AF_INET6][0]['addr']
        if not ip_info:
            return "No IPv4 or IPv6 address found."
        return ip_info
    except ValueError:
        return "Interface not found or doesn't have an IP address."

interface_name = 'eth0'  # Replace with your interface name

ip_address = get_ip_address(interface_name)

print(f"IP Address of {interface_name}: {ip_address}")
  1. Fetching Address Information: The function begins by retrieving all addresses associated with the given interface using netifaces.ifaddresses(interface).
  2. IPv4 and IPv6 Address Check: It then checks if the interface has IPv4 (netifaces.AF_INET) and/or IPv6 (netifaces.AF_INET6) addresses and stores them in the ip_info dictionary.
  3. No Address Found: If no IPv4 or IPv6 addresses are found for the interface, the function returns a message indicating this.
  4. Returning IP Information: If valid IP addresses are found, the ip_info dictionary containing these addresses is returned.
  5. Specifying the Interface: The interface_name variable is set to 'eth0' (or any other interface name as required). This is the network interface for which the IP address(es) will be retrieved.
  6. Function Call: get_ip_address(interface_name) is called with the specified interface name. The function returns the IP address information for that interface.
  7. Output: The script prints out the IP address information. If the specified interface has an IPv4 or IPv6 address, it will be displayed; otherwise, an appropriate message indicating the absence of an IP address or an error will be shown.

Best Practices for IP Address Retrieval in Python Networking

Effective network scripting in Python hinges on choosing the right tools for your needs:

  1. Internal vs. External IP Retrieval:
  2. Use socket and netifaces for internal IP address tasks within a local network.
  3. Use external IP retrieval such as ipify or Abstract API for applications that interact with the wider internet or for remote access.
  4. IPv4 and IPv6 Compatibility:
  5. Ensure your network applications support both IPv4 and IPv6, balancing current needs with future-proofing for IPv6's growing adoption.
  6. Using Public IP Services Carefully:
  7. Be mindful of privacy and reliability when using external services for public IP retrieval. Consider potential service limitations and security implications.
  8. Robust Error Handling:
  9. Implement robust error handling for network operations and test your applications across different network scenarios.

By understanding and applying these practices, you can develop robust and secure network applications in Python that effectively handle both local and internet-facing networking tasks.

FAQ

Q. How do I find my public IP address using Python?
A. You can find your public IP address in Python by making a GET request to an external service like ipify using the requests module.

Q. Can Python retrieve both IPv4 and IPv6 addresses?
A. Yes, Python can retrieve both IPv4 and IPv6 addresses. The socket module can be used for local address retrieval, and netifaces provides a more detailed approach for network interface information.

Q. What libraries are needed to find an IP address in Python?
A. To find IP addresses in Python, the socket library (part of Python's standard library) is used for local IP addresses. For external IP addresses, the requests library is helpful. Additionally, netifaces can be used for detailed network interface information.

Q. How can I handle errors when retrieving IP addresses in Python?
A. Implement try...except blocks for error handling. For instance, when using the requests library for external IP retrieval, catch exceptions like requests.RequestException to handle connectivity issues, timeouts, or HTTP errors.

Q. Is it possible to fetch the geographical location of an IP address in Python?
A. Yes, you can fetch the geographical location of an IP address by using external APIs such as AbstractAPI's IP Geolocation service. This requires sending a request to the API and parsing the response.

Q. How do I choose between internal and external IP address retrieval methods?
A. Choose internal IP address retrieval (using socket or netifaces) for local network configurations and tasks. Opt for external IP retrieval (using services like Abstract API) when you need to know how your system is accessed from the internet, such as for remote server access or network monitoring.

What now?

Now that you've learned how to retrieve your IP address using Python, it's time to put your new skills into practice. Here are some real-world applications where knowing how to find an IP address can be incredibly useful:

Network Diagnostics: Use your Python script to troubleshoot network issues by verifying the IP addresses of your devices within a computer network.

Server Configuration: When setting up servers, especially in a Linux environment, you'll often need to know the server's local IP to configure network settings.

Developing Web Applications: If you're a beginner in Python web development, you can use the IP address to implement user-specific features based on their location or to enhance security by logging IP data.

Internet of Things (IoT): For those working with IoT devices, such as routers or home automation systems, retrieving the local IP can help in device management and network configuration.

Whether you're a software developer, network administrator, or just starting out, understanding IP addresses and how to retrieve them using Python is a valuable skill. The socket module is your gateway to network programming in Python, and with the power of Python 3, you can easily write scripts that interact with your operating system and networking interfaces.

If you're ready to take your skills to the next level, consider diving into topics like TCP/IP, domain name resolution with DNS, or even automating network tasks with Python scripts.

Links

Here are a few resources to help you on your journey.

Python Socket documentation
https://docs.python.org/3/library/socket.html

Requests Module Documentation:
https://pypi.org/project/requests/

AbstractAPI — Free Geolocation API service
https://docs.abstractapi.com/ip-geolocation

Netifaces Module Documentation:
https://0xbharath.github.io/python-network-programming/libraries/netifaces/index.html

4.5/5 stars (11 votes)

Nick Johnson
Nick Johnson is a seasoned technical writer with a flair for transforming complex technical subjects into engaging narratives. With a rich background at Microsoft Ads and HP's internal help desk, Nick combines his technical expertise, particularly in Python, with a keen eye for style and narrative to deliver content that resonates with a diverse audience.
Get your free
IP Geolocation API
API
key now
Enhance your IP geolocation capabilities by trying Abstract's IP Geolocation API. It's an effortless way to access detailed IP address information, perfect for both beginners and seasoned developers.
get started for free

Related Articles

Get your free
API
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required