import sys, os
import socket, struct, fcntl
import six
import psutil
def get_ip(iface="enp0s3"):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockfd = sock.fileno()
SIOCGIFADDR = 0x8915
if six.PY3:
ifreq = struct.pack('16sH14s', iface.encode(encoding="utf-8"), socket.AF_INET,
('\x00' * 14).encode(encoding="utf-8"))
else:
ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00' * 14)
try:
res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
except Exception as e:
return
ip = struct.unpack('16sH2x4s8x', res)[2]
return socket.inet_ntoa(ip)
def main():
network_list = psutil.net_io_counters(pernic=True)
for net_name in network_list:
interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
"enp0s3",
"bond0"
]
if net_name in interfaces:
ip = get_ip()
if ip:
print(net_name, ip)
if __name__ == "__main__":
main()