# vim get_ip.py

# -*- coding: utf-8 -*-
#complete local network card IP
#need install netifaces modem
def GetNetworkIP():
    #get local network card ip address 
    import netifaces
    routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0]   #gateway
    routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]   #NA(network adapter)information

    for interface in netifaces.interfaces():
        if interface == routingNicName:
        #print (netifaces.ifaddresses(interface))
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']   #get IP
            except KeyError:
                pass
    #print ("Routing IP Address:%s"% routingIPAddr)
    return routingIPAddr
if __name__ == "__main__":
    try:
        print ("Routing IP Address:",GetNetworkIP())
    except:
        print ("Unable to get the address, there may not be installed netifaces module! command: pip install netifaces")

 

#python get_ip.py

('Routing IP Address:', '192.xx.xx.xx')

 

参考文献:http://blog.51cto.com/sunday208/1875822

posted on 2018-07-30 10:09  宅女士  阅读(754)  评论(0编辑  收藏  举报