Retrieving network mask in Python

前端 未结 8 968
不知归路
不知归路 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 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.

提交回复
热议问题