How to convert a CIDR prefix to a dotted-square netmask in Python?

How to convert a CIDR prefix to a dotted-square netmask in Python?

For example, if 12I need to return the prefix 255.240.0.0.

+4
source share
3 answers

You can do it as follows:

def cidr(prefix):
    return socket.inet_ntoa(struct.pack(">I", (0xffffffff << (32 - prefix)) & 0xffffffff))
+5
source

Here is the lighter side solution (no dependencies between modules):

netmask = '.'.join([str((0xffffffff << (32 - len) >> i) & 0xff)
                    for i in [24, 16, 8, 0]])
+9
source

:

netmask = 0xFFFFFFFF & (2**(32-len)-1)

, F:

netmask = (2**32-1) & ~ (2 ** (32-len)-1)

( ):

netmask = (1<<32)-1 & ~ ((1 << (32-len))-1)

dotted.quad, inet.ntoa . : 'len' , .

0

Source: https://habr.com/ru/post/1538487/


All Articles