Retrieving network mask in Python

前端 未结 8 961
不知归路
不知归路 2021-01-05 07:59

How would one go about retrieving a network device\'s netmask (In Linux preferably, but if it\'s cross-platform then cool)? I know how in C on Linux but I can\'t find a way

8条回答
  •  迷失自我
    2021-01-05 08:06

    The netifaces module deserves a mention here. Straight from the docs:

    >>> netifaces.interfaces()
    ['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']
    
    >>> addrs = netifaces.ifaddresses('en0')
    >>> addrs[netifaces.AF_INET]
    [{'broadcast': '10.15.255.255', 'netmask': '255.240.0.0', 'addr': '10.0.1.4'}, {'broadcast': '192.168.0.255', 'addr': '192.168.0.47'}]
    

    Works on Windows, Linux, OS X, and probably other UNIXes.

提交回复
热议问题