Python 3: create a list of possible ip addresses from a CIDR notation

后端 未结 7 879
花落未央
花落未央 2020-12-08 07:57

I have been handed the task of creating a function in python (3.1) that will take a CIDR notation and return the list of possible ip addresses. I have looked around python.

相关标签:
7条回答
  • 2020-12-08 08:45

    I would prefer to do a little math rather than to install an external module, no one has the same taste with me?

    #!/usr/bin/env python
    # python cidr.py 192.168.1.1/24
    
    import sys, struct, socket
    
    (ip, cidr) = sys.argv[1].split('/')
    cidr = int(cidr) 
    host_bits = 32 - cidr
    i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
    start = (i >> host_bits) << host_bits # clear the host bits
    end = start | ((1 << host_bits) - 1)
    
    # excludes the first and last address in the subnet
    for i in range(start, end):
        print(socket.inet_ntoa(struct.pack('>I',i)))
    
    0 讨论(0)
提交回复
热议问题