Comment obtenir l'adresse IP d'une interface réseau en Python sans aucune bibliothèque

L’exemple de code suivant obtiendra l’adresse IPv4 pour l’interface réseau locale eth0 :

get_interface_ip.py
import subprocess
import re

def get_interface_ip(interface):
    """Obtient l'adresse IP pour une interface réseau donnée"""
    command = f"ip addr show {interface}"
    output = subprocess.check_output(command, shell=True).decode()

    ip_pattern = r'inet\s+(\d+\.\d+\.\d+\.\d+)'
    match = re.search(ip_pattern, output)

    if match:
        ip_address = match.group(1)
        return ip_address
    else:
        return None

interface_name = "eth0"
ip_address = get_interface_ip(interface_name)

if ip_address:
    print(f"IP address of {interface_name}: {ip_address}")
else:
    print(f"No IP address found for {interface_name}")

Exemple de sortie :

ip_address_output.txt
IP address of eth0: 192.168.178.221

Consultez les articles similaires par catégorie : Python