Search code examples
pythoncidrnetmask

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


How can I convert a CIDR prefix to a dotted-quad netmask in Python?

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


Solution

  • You can do it like this:

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