Skip to content

Instantly share code, notes, and snippets.

@EONRaider
Last active August 17, 2024 18:47
Show Gist options
  • Save EONRaider/3b7a8ca433538dc52b09099c0ea92745 to your computer and use it in GitHub Desktop.
Save EONRaider/3b7a8ca433538dc52b09099c0ea92745 to your computer and use it in GitHub Desktop.
Get the IP address of a network interface in Python 3
#!/usr/bin/env python3
# https://gist.github.com/EONRaider/3b7a8ca433538dc52b09099c0ea92745
__author__ = 'EONRaider, keybase.io/eonraider'
import fcntl
import socket
import struct
try:
from netifaces import AF_INET, ifaddresses
except ModuleNotFoundError as e:
raise SystemExit(f"Requires {e.name} module. Run 'pip install {e.name}' "
f"and try again.")
def get_ip_linux(interface: str) -> str:
"""
Uses the Linux SIOCGIFADDR ioctl to find the IP address associated
with a network interface, given the name of that interface, e.g.
"eth0". Only works on GNU/Linux distributions.
Source: https://bit.ly/3dROGBN
Returns:
The IP address in quad-dotted notation of four decimal integers.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
packed_iface = struct.pack('256s', interface.encode('utf_8'))
packed_addr = fcntl.ioctl(sock.fileno(), 0x8915, packed_iface)[20:24]
return socket.inet_ntoa(packed_addr)
def get_ip_cross(interface: str) -> str:
"""
Cross-platform solution that should work under Linux, macOS and
Windows.
"""
return ifaddresses(interface)[AF_INET][0]['addr']
@interfan7
Copy link

interfan7 commented Sep 21, 2023

Thanks!

For get_ip_linux(), maybe with statement is even better, as it would close the socket upon completion or exception:

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as ssock:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment