Generating IP-Address Range


I have a dict{} with ip-addresses, from and to IP.

All are strings, I want to maintain first 3 bytes of IP, and generate last byte up until n.n.n.X all inclusive.
However I cannot convert this string to an Int or Float number as multiple decimals exist. And should remain as string in dict{} as they are parsed instances from another class.

Current method:

def ipSorting(self):
    for key in self.zIpRangeDictionary:
        zn = self.zIpRangeDictionary[key]
        print zn.get_zoneFromIp(), '--->', zn.get_zoneToIp()

Current output: ---> ---> ---> ---> --->


A breakdown of ip address is:

netByte1 = Word(nums) + fStop
netByte2 = Word(nums) + fStop
zoneByte = Word(nums)
hostByte = fStop + Word(nums)

ipAddr = Combine(netByte1 + netByte2 + zoneByte + hostByte)

So than when rule in parsing, and is successfully matched with input, it adds ipAddress1 and ipAddress2 into a dict, from which I further should generate all inclusive addresses.

zoneIpRule = zoneName + frm + ipAddr + to + ipAddr
   def zoneIpAction(s, loc, toks):
       zoneIpRange = ZoneIpRange(toks[0], toks[2], toks[4])
       self.ast.zIpRangeDictionary[toks[0]] = zoneIpRange

Method above stores ipAddress into dict{} as instances, for which I have written get methods to retrieve those addresses so I can reuse them and do something with them.


Assuming you are storing it in your dictionary in the form ip_from:ip_to then you can have a simple implementation like this:

ip_to = ''
ip_from = ''
ip_dict = {ip_from:ip_to}
addresses = []
for ip_from,ip_to in ip_dict.iteritems():
    for quad in xrange(int(ip_from.split('.')[3]),int(ip_to.split('.')[3])+1):

Where the list addresses will have all your IP’s.

Answered By – Rudresh Panchal

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.