#!/usr/bin/env python3

import os
import sys
import subprocess
import socket
import fcntl
import struct

SYS_PATH = '/sys/class/net'


def _read_file(file):
    source = open(file, 'r')
    content = source.read()
    source.close()
    return content


def get_connected(interface):
    STATUS = ('No', 'Yes')
    carrier_file = os.path.join(SYS_PATH, interface, 'carrier')

    carrier = 0
    try:
        carrier = int(_read_file(carrier_file))
    except IOError:
        pass

    return STATUS[carrier]


def get_ip_address(interface):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', interface[:15].encode())
    )[20:24])

def get_ipv6_address(interface):
    cmd = ['/sbin/ip', '-6', 'addr', 'show', 'dev', interface]
    proc = subprocess.check_output(cmd,universal_newlines=True)
    ipaddr = proc.split()[8].strip()
    return ipaddr


def get_mac_address(interface):
    address_file = os.path.join(SYS_PATH, interface, 'address')

    address = ''
    try:
        address = _read_file(address_file)
    except IOError:
        pass

    return address


def main(args):
    for interface in args:
        connected = get_connected(interface)
        print("Interface: %s" % interface)
        print("Connected: %s" % connected)
        try:
            print("IPv4: %s" % get_ip_address(interface))	
        except IOError:
            print("IPv4: n/a")
        try:    
            print("IPv6: %s" % get_ipv6_address(interface))	
        except IOError:
            print("IPv6: n/a")
        except:    
            print("IPv6: n/a")
        print("MAC: %s\n" % get_mac_address(interface))

    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
