Finding local IP addresses using Python's stdlib

后端 未结 30 2616
北恋
北恋 2020-11-21 23:54

How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

30条回答
  •  一整个雨季
    2020-11-22 00:37

    A slight refinement of the commands version that uses the IP command, and returns IPv4 and IPv6 addresses:

    import commands,re,socket
    
    #A generator that returns stripped lines of output from "ip address show"
    iplines=(line.strip() for line in commands.getoutput("ip address show").split('\n'))
    
    #Turn that into a list of IPv4 and IPv6 address/mask strings
    addresses1=reduce(lambda a,v:a+v,(re.findall(r"inet ([\d.]+/\d+)",line)+re.findall(r"inet6 ([\:\da-f]+/\d+)",line) for line in iplines))
    #addresses1 now looks like ['127.0.0.1/8', '::1/128', '10.160.114.60/23', 'fe80::1031:3fff:fe00:6dce/64']
    
    #Get a list of IPv4 addresses as (IPstring,subnetsize) tuples
    ipv4s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if '.' in addr)]
    #ipv4s now looks like [('127.0.0.1', 8), ('10.160.114.60', 23)]
    
    #Get IPv6 addresses
    ipv6s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if ':' in addr)]
    

提交回复
热议问题