SoFunction
Updated on 2025-04-11

Python script implementation to obtain IP address

1. Script function

1. Get the host name

2. Obtain the external network IP (try through multiple public APIs) IPV4 and IPV6

3. Obtain the intranet IP of all network interfaces

4. Save to file and print information

Output example:

Host Name: MyComputer

Intranet IPv4 address:
  - 192.168.1.100
  - 192.168.56.1

Intranet IPv6 address:
  - 2001:0db8:85a3:0000:0000:8a2e:0370:7334

Foreign network IPv4: 203.0.113.1
Foreign network IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334

2. Things to note

1. The network connection is required to obtain the external network IP

2. Some network environments may block access to IP query services

3. If in a proxy or VPN environment, the obtained external network IP may be the proxy or VPN IP.

4. There may be multiple intranet IP, especially when there are multiple network interfaces.

5. Consider temporarily closing the firewall

6. If your network does not support IPv6, the relevant IPv6 address will be displayed as "Unable to obtain"

7. Some systems may require administrator permissions to obtain complete network interface information.

3. Preparation

Import the library:

import socket
import requests
import json
import time
from datetime import datetime

4. Complete code

import socket
import requests
import json
import time
from datetime import datetime
 
 
def get_external_ipv4():
    """Get the IPv4 address of the external network"""
    apis = [
        {
            'url': '?format=json',
            'timeout': 5,
            'headers': {'User-Agent': 'Mozilla/5.0'},
            'json': True,
            'key': 'ip'
        },
        {
            'url': '?format=json',
            'timeout': 5,
            'headers': {'User-Agent': 'Mozilla/5.0'},
            'json': True,
            'key': 'ip'
        },
        {
            'url': '',
            'timeout': 5,
            'headers': {'User-Agent': 'curl/7.64.1'}
        }
    ]
 
    for api in apis:
        try:
            print(f"Try from {api['url']} Get the external networkIPv4...")
            response = (
                url=api['url'],
                timeout=api['timeout'],
                headers=api['headers']
            )
 
            if response.status_code == 200:
                if ('json'):
                    data = ()
                    return data[api['key']]
                else:
                    return ()
 
        except Exception as e:
            print(f"The current interface request failed: {str(e)}")
            continue
 
    return "Unable to obtainIPv4address"
 
 
def get_external_ipv6():
    """Get the IPv6 address of the external network"""
    apis = [
        {
            'url': '?format=json',
            'timeout': 5,
            'headers': {'User-Agent': 'Mozilla/5.0'},
            'json': True,
            'key': 'ip'
        },
        {
            'url': '',
            'timeout': 5,
            'headers': {'User-Agent': 'curl/7.64.1'}
        }
    ]
 
    for api in apis:
        try:
            print(f"Try from {api['url']} Get the external networkIPv6...")
            response = (
                url=api['url'],
                timeout=api['timeout'],
                headers=api['headers']
            )
 
            if response.status_code == 200:
                if ('json'):
                    data = ()
                    return data[api['key']]
                else:
                    return ()
 
        except Exception as e:
            print(f"The current interface request failed: {str(e)}")
            continue
 
    return "Unable to obtainIPv6address"
 
 
def get_internal_ips():
    """Get the intranet IP address (get IPv4 and IPv6 at the same time)"""
    internal_ips = {'ipv4': [], 'ipv6': []}
 
    try:
        # Get all IPs of all network interfaces        hostname = ()
        addrs = (hostname, None)
 
        for addr in addrs:
            ip = addr[4][0]
            # Determine whether it is an IPv6 address            if ':' in ip:
                if not ('fe80:') and not ('::1'):
                    if ip not in internal_ips['ipv6']:
                        internal_ips['ipv6'].append(ip)
            else:
                if not ('127.'):
                    if ip not in internal_ips['ipv4']:
                        internal_ips['ipv4'].append(ip)
 
        # Use alternate method to obtain IPv4        if not internal_ips['ipv4']:
            try:
                s = (socket.AF_INET, socket.SOCK_DGRAM)
                (("8.8.8.8", 80))
                ip = ()[0]
                ()
                if ip not in internal_ips['ipv4']:
                    internal_ips['ipv4'].append(ip)
            except:
                pass
 
    except Exception as e:
        print(f"Get the intranetIPAn error occurred: {str(e)}")
 
    return internal_ips
 
 
def save_to_file(data):
    """Save information to file"""
    try:
        with open('../Office and Multimedia/ip_info.txt', 'a', encoding='utf-8') as f:
            (f"\n{'=' * 50}\n")
            (f"Test time: {().strftime('%Y-%m-%d %H:%M:%S')}\n")
            (f"Host Name: {data['hostname']}\n\n")
 
            ("Intranet IPv4 address:\n")
            for ip in data['internal_ipv4']:
                (f"  - {ip}\n")
 
            ("\nIntranet IPv6 address:\n")
            for ip in data['internal_ipv6']:
                (f"  - {ip}\n")
 
            (f"\nExternal networkIPv4: {data['external_ipv4']}\n")
            (f"External networkIPv6: {data['external_ipv6']}\n")
            (f"{'=' * 50}\n")
 
    except Exception as e:
        print(f"保存文件时An error occurred: {str(e)}")
 
 
def main():
    try:
        print("Start to get network information...\n")
 
        # Get the host name        hostname = ()
        print(f"Host Name: {hostname}\n")
 
        # Obtain the intranet IP        internal_ips = get_internal_ips()
        print("Intranet IPv4 address:")
        for ip in internal_ips['ipv4']:
            print(f"  - {ip}")
 
        print("\nIntranet IPv6 address:")
        for ip in internal_ips['ipv6']:
            print(f"  - {ip}")
 
        # Obtain the external network IP        print("\nGetting external network IP...")
        external_ipv4 = get_external_ipv4()
        external_ipv6 = get_external_ipv6()
 
        print(f"\nExternal networkIPv4: {external_ipv4}")
        print(f"External networkIPv6: {external_ipv6}")
 
        # Save information to file        data = {
            'hostname': hostname,
            'internal_ipv4': internal_ips['ipv4'],
            'internal_ipv6': internal_ips['ipv6'],
            'external_ipv4': external_ipv4,
            'external_ipv6': external_ipv6
        }
        save_to_file(data)
        print("\nInformation has been saved to ip_info.txt file")
 
    except Exception as e:
        print(f"程序执行An error occurred: {str(e)}")
 
 
if __name__ == "__main__":
    # Make sure the requests library is installed    # pip install requests
 
    main()
 
    # Wait for the user to exit by pressing the button    input("\nPress Enter to exit...")

The above is the detailed content of Python scripts to obtain IP addresses. For more information about Python obtaining IP addresses, please follow my other related articles!