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.
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
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 :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With