2022-07-05 05:14:37 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""Network utils"""
|
|
|
|
import subprocess
|
|
|
|
import re
|
2024-03-01 11:58:28 +00:00
|
|
|
import ipaddress
|
2022-08-25 17:03:56 +00:00
|
|
|
from typing import Optional
|
2022-07-05 05:14:37 +00:00
|
|
|
|
2022-07-07 13:53:19 +00:00
|
|
|
|
2022-08-25 17:03:56 +00:00
|
|
|
def get_ip4() -> str:
|
2022-07-05 05:14:37 +00:00
|
|
|
"""Get IPv4 address"""
|
|
|
|
try:
|
2022-07-07 13:53:19 +00:00
|
|
|
ip4 = subprocess.check_output(["ip", "addr", "show", "dev", "eth0"]).decode(
|
|
|
|
"utf-8"
|
|
|
|
)
|
2022-07-05 05:14:37 +00:00
|
|
|
ip4 = re.search(r"inet (\d+\.\d+\.\d+\.\d+)\/\d+", ip4)
|
|
|
|
except subprocess.CalledProcessError:
|
|
|
|
ip4 = None
|
2022-08-25 17:03:56 +00:00
|
|
|
return ip4.group(1) if ip4 else ""
|
2022-07-05 05:14:37 +00:00
|
|
|
|
2022-07-07 13:53:19 +00:00
|
|
|
|
2024-03-01 00:21:31 +00:00
|
|
|
def get_ip6() -> Optional[str]:
|
2022-07-05 05:14:37 +00:00
|
|
|
"""Get IPv6 address"""
|
|
|
|
try:
|
2024-03-03 21:45:45 +00:00
|
|
|
ip6_addresses = subprocess.check_output(
|
|
|
|
["ip", "addr", "show", "dev", "eth0"]
|
|
|
|
).decode("utf-8")
|
2024-03-01 12:06:32 +00:00
|
|
|
ip6_addresses = re.findall(r"inet6 (\S+)\/\d+", ip6_addresses)
|
|
|
|
for address in ip6_addresses:
|
2024-03-01 11:58:28 +00:00
|
|
|
if ipaddress.IPv6Address(address).is_global:
|
|
|
|
return address
|
2022-07-05 05:14:37 +00:00
|
|
|
except subprocess.CalledProcessError:
|
2024-03-01 11:58:28 +00:00
|
|
|
return None
|