Last modified: Apr 27, 2025 By Alexander Williams

Find Local IP Address in Python (IPv4/IPv6)

Knowing your local IP address is useful for network programming. Python makes it easy to find both IPv4 and IPv6 addresses.

Why Find Your Local IP Address?

Local IP addresses help in network configuration. They are needed for server setups, peer-to-peer apps, and debugging.

You might need it when restricting access by IP in Flask or handling multiple connections with AsyncIO.

Method 1: Using the socket Module

The socket module is Python's standard way to handle network connections. Here's how to get your local IP:


import socket

def get_local_ip():
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    return local_ip

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


Local IPv4 Address: 192.168.1.5

Note: This only returns IPv4 addresses. It may return 127.0.0.1 (localhost) on some systems.

Method 2: Getting All IP Addresses

For both IPv4 and IPv6, use this improved method:


import socket

def get_all_ips():
    ips = []
    hostname = socket.gethostname()
    for addr in socket.getaddrinfo(hostname, None):
        ips.append(addr[4][0])
    return list(set(ips))  # Remove duplicates

print("All IP Addresses:", get_all_ips())


All IP Addresses: ['192.168.1.5', 'fe80::1%lo0']

Method 3: Using the netifaces Module

For more detailed network information, install the netifaces module:


import netifaces

def get_interface_ips():
    interfaces = netifaces.interfaces()
    ips = []
    for interface in interfaces:
        addrs = netifaces.ifaddresses(interface)
        if netifaces.AF_INET in addrs:
            ips.extend([addr['addr'] for addr in addrs[netifaces.AF_INET]])
        if netifaces.AF_INET6 in addrs:
            ips.extend([addr['addr'] for addr in addrs[netifaces.AF_INET6]]])
    return ips

print("Interface IPs:", get_interface_ips())


Interface IPs: ['127.0.0.1', '192.168.1.5', 'fe80::1%lo0']

This method gives you more control. It shows IPs for each network interface separately.

Understanding IPv4 vs IPv6

IPv4 addresses look like 192.168.1.1. IPv6 addresses are longer, like fe80::1%lo0.

You can detect private vs public IPs in Python if needed.

Common Issues and Solutions

Problem: Only getting 127.0.0.1 (localhost).

Solution: Try the netifaces method or check your network connection.

Problem: No IPv6 address returned.

Solution: Ensure your network supports IPv6 and is configured properly.

Conclusion

Finding your local IP in Python is simple with the right tools. The socket module works for basic cases.

For advanced needs, netifaces provides detailed interface information. These methods help in network programming and debugging.

Remember these techniques when working with socket binding or network applications.