Skip to content

Instantly share code, notes, and snippets.

@thejasonfisher
Forked from EONRaider/get_ip_address.py
Created September 14, 2023 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejasonfisher/8d7c515f91993070800f839d2b4561eb to your computer and use it in GitHub Desktop.
Save thejasonfisher/8d7c515f91993070800f839d2b4561eb 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']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment