Get IP Mask from IP Address and Mask Length in Python

前端 未结 2 1138
渐次进展
渐次进展 2021-01-03 05:28

Given an IP Address in dotted quad notation, for example:
192.192.45.1
And a mask length for example 8, 16, 24 typically, but could be anything i.e. 17.

Ca

2条回答
  •  猫巷女王i
    2021-01-03 06:01

    You can calcuate the 32 bit value of the mask like this

    (1<<32) - (1<<32>>mask_length)
    

    eg.

    >>> import socket, struct
    >>> mask_length = 24
    >>> mask = (1<<32) - (1<<32>>mask_length)
    >>> socket.inet_ntoa(struct.pack(">L", mask))
    '255.255.255.0'
    

提交回复
热议问题