Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python networking : find MAC address for corresponding interfaces

I has found a scripts from pmav99. Big thanks to him.

import socket
import psutil

def get_ip_addresses(family):
    for interface, snics in psutil.net_if_addrs().items():
        for snic in snics:
            if snic.family == family:
                yield (interface, snic.address, snic.netmask)

ipv4s = list(get_ip_addresses(socket.AF_INET))

print ipv4s

The result is :

[('Local Area Connection* 2', '169.254.189.147', '255.255.0.0'), ('Ethernet', '192.168.18.34', '255.255.255.0'), ('Wi-Fi', '192.168.1.102', '255.255.255.0'), ('Loopback Pseudo-Interface 1', '127.0.0.1', '255.0.0.0')]

But in net_if_addrs() of psutil, it also provide mac-address of each interfaces. So how can i add the mac address to the list ? the keys name of MAC address also is address. I can't find the way to get it.

like image 799
Park Yo Jin Avatar asked Jun 15 '26 00:06

Park Yo Jin


2 Answers

According to the documentation, MAC addresses are noted by family psutil.AF_LINK. This code fragment will get a list of interface names, along with the MAC addresses.

macs = list(get_ip_addresses(psutil.AF_LINK))
print macs

The following program will produce a mapping from MAC addresses to IPV4 addresses:

import socket
import psutil

def get_ip_addresses(family):
    for interface, snics in psutil.net_if_addrs().items():
        for snic in snics:
            if snic.family == family:
                yield (interface, (snic.address, snic.netmask))

ipv4s = dict(get_ip_addresses(socket.AF_INET))
macs = dict(get_ip_addresses(psutil.AF_LINK))
mac2ipv4 = {macs[k][0]: ipv4s[k] for k in set(macs) & set(ipv4s)}

print mac2ipv4
like image 73
Robᵩ Avatar answered Jun 16 '26 12:06

Robᵩ


i find a simply way to get the result that i want

import socket
import psutil

def get_ip_addresses(family):
    for interface, snics in psutil.net_if_addrs().items():
        for snic in snics:
            if snic.family == -1 :
                mac = snic.address
            if snic.family == 2 :
                yield (interface, snic.address, snic.netmask, mac)

ipv4 = list(get_ip_addresses(socket.AF_INET))

print ipv4

and the result look like this :

[('Local Area Connection* 2', '169.254.189.147', '255.255.0.0', '34-F3-9A-4C-D0-C5'), ('Ethernet', '192.168.18.34', '255.255.255.0', 'C8-5B-76-AC-B7-BC'), ('Wi-Fi', '192.168.1.106', '255.255.255.0', '34-F3-9A-4C-D0-C4'), ('Loopback Pseudo-Interface 1', '127.0.0.1', '255.0.0.0', '00-00-00-00-00-00-00-E0')]

Connection name with corresponding ipv4, netmask and mac address. Hope it helpful for orther visitor :).

like image 30
Park Yo Jin Avatar answered Jun 16 '26 14:06

Park Yo Jin