Skip to content

Instantly share code, notes, and snippets.

@pklaus
Last active October 22, 2025 17:41
Show Gist options
  • Select an option

  • Save pklaus/289646 to your computer and use it in GitHub Desktop.

Select an option

Save pklaus/289646 to your computer and use it in GitHub Desktop.
Python: List all Network Interfaces On Computer
"""
Determine IPv4 addresses on a Linux machine via the socket interface.
Thanks @bubthegreat the changes to make it Py2/3 compatible and the helpful
code comments: https://gist.github.com/pklaus/289646#gistcomment-2396272
This version has all comments removed for brevity.
"""
import socket
import array
import struct
import fcntl
def get_local_interfaces():
""" Returns a dictionary of name:ip key value pairs. """
MAX_BYTES = 4096
FILL_CHAR = b'\0'
SIOCGIFCONF = 0x8912
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', MAX_BYTES * FILL_CHAR)
names_address, names_length = names.buffer_info()
mutable_byte_buffer = struct.pack('iL', MAX_BYTES, names_address)
mutated_byte_buffer = fcntl.ioctl(sock.fileno(), SIOCGIFCONF, mutable_byte_buffer)
max_bytes_out, names_address_out = struct.unpack('iL', mutated_byte_buffer)
namestr = names.tobytes()
namestr[:max_bytes_out]
bytes_out = namestr[:max_bytes_out]
ip_dict = {}
for i in range(0, max_bytes_out, 40):
name = namestr[ i: i+16 ].split(FILL_CHAR, 1)[0]
name = name.decode('utf-8')
ip_bytes = namestr[i+20:i+24]
full_addr = []
for netaddr in ip_bytes:
if isinstance(netaddr, int):
full_addr.append(str(netaddr))
elif isinstance(netaddr, str):
full_addr.append(str(ord(netaddr)))
ip_dict[name] = '.'.join(full_addr)
return ip_dict
if __name__ == "__main__":
for iface, ip in get_local_interfaces().items():
print("{ip:15s} {iface}".format(ip=ip, iface=iface))
@pklaus
Copy link
Author

pklaus commented Jun 10, 2021

impossible to get fcntl module when I import it

Why?

Impossible to answer if you don't state the operating system you're on and the Python version you're using.

@rezgui
Copy link

rezgui commented Oct 22, 2025

#!/usr/bin/python3

import ifaddr

adapters = ifaddr.get_adapters()

print("List of Network Interfaces:")
for adapter in adapters:
    print(f"  Adapter Name: {adapter.nice_name}")
    print(f"  Description: {adapter.name}")
    print(f"  MAC Address: {adapter.ips[0].mac if hasattr(adapter.ips[0], 'mac') else 'N/A'}")

    # You can further filter for specific interface types if needed
    # For example, to only show interfaces likely to be Ethernet:
    # if "Ethernet" in adapter.nice_name or "eth" in adapter.name:
    #     print(f"    (Likely Ethernet Interface)")

    for ip in adapter.ips:
        print(f"    IP Address: {ip.ip}/{ip.network_prefix}")
    print("-" * 20)

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