Generating IP-Address Range

Issue

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:

192.168.1.1 ---> 192.168.1.10
192.168.2.1 ---> 192.168.2.10
192.168.3.1 ---> 192.168.3.10
192.168.4.1 ---> 192.168.4.10
192.168.5.1 ---> 192.168.5.10

Required:

192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
etc.

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
   zoneIpRule.setParseAction(zoneIpAction)

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.

Solution

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 = '192.168.1.10'
ip_from = '192.168.1.1'
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):
        addresses.append('.'.join(ip_to.split('.')[:3])+'.'+str(quad))

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.