Retrieving network mask in Python

前端 未结 8 957
不知归路
不知归路 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:22

    Using the python pyroute2 library you can get all network element attributes:

    from pyroute2 import IPRoute
    ip = IPRoute()
    info = [{'iface': x['index'], 'addr': x.get_attr('IFA_ADDRESS'), 'mask':  x['prefixlen']} for x in ip.get_addr()]
    

    More information available here:http://pyroute2.org/pyroute2-0.3.14p4/iproute.html

    0 讨论(0)
  • 2021-01-05 08:22

    Using socket and ipaddress

    From the documentation

    ipaddress provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks.
     The functions and classes in this module make it straightforward to handle various tasks related to IP addresses ...

    >>> import socket
    >>> import ipaddress
    >>>
    >>> ip_addr = socket.gethostbyname(socket.gethostname())
    >>> netmask = ipaddress.IPv4Network(ip_addr).netmask
    >>> print(netmask)
    255.255.255.255
    >>> ...
    

    This may question may be answered here. It is not the same question,but also offers a solution to your question.

    0 讨论(0)
提交回复
热议问题