Finding local IP addresses using Python's stdlib

后端 未结 30 2589
北恋
北恋 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:26

    You can use the netifaces module. Just type:

    pip install netifaces
    

    in your command shell and it will install itself on default Python installation.

    Then you can use it like this:

    from netifaces import interfaces, ifaddresses, AF_INET
    for ifaceName in interfaces():
        addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
        print '%s: %s' % (ifaceName, ', '.join(addresses))
    

    On my computer it printed:

    {45639BDC-1050-46E0-9BE9-075C30DE1FBC}: 192.168.0.100
    {D43A468B-F3AE-4BF9-9391-4863A4500583}: 10.5.9.207

    Author of this module claims it should work on Windows, UNIX and Mac OS X.

提交回复
热议问题