K
K
KPEBETKA2014-02-08 16:43:56
Python
KPEBETKA, 2014-02-08 16:43:56

Python. Ugly While construction. Can it be simplified?

There is a function:

def wildcard_iprange(ipaddr, sw):

  if sw:
    beginning = [ int(i) if not '-' in i else int(i.split('-')[0]) for i in ipaddr.split('.') ]
    e = [ int(i) if not '-' in i else int(i.split('-')[1]) for i in ipaddr.split('.') ]
    b = beginning[:]
  else:
    beginning = [ int(i) if i != '*' else 0 for i in ipaddr.split('.') ]
    e = [ int(i) if i != '*' else 255 for i in ipaddr.split('.') ]
    b = beginning[:]

  while b[0] <= e[0]:
    while b[1] <= e[1]:
      while b[2] <= e[2]:
        while b[3] <= e[3]:
          yield '%s.%s.%s.%s' % (b[0], b[1], b[2], b[3])
          b[3] = b[3] + 1
        b[2] = b[2] + 1
        b[3] = beginning[3]
      b[1] = b[1] + 1
      b[2] = beginning[2]
    b[0] = b[0] + 1
    b[1] = beginning[1]

This function returns ip-addresses based on what mask was passed during the call.
A few examples of what can be transmitted:
192.168.1.*
192.168.*.*
192.*.1.*
....
Or
192.168.1-3.0-254
192-255.168.4-5.0-2
... .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
maxfox, 2014-02-09
@KPEBETKA

Your noodles are notable ..
I understand correctly that you just need to display all ip by mask?

import itertools

s = '197.1-10.197.*'
sections = s.split('.')
addresses = []
for i in sections:
  if '-' in i:
    min,max = i.split('-')
    a = [x for x in range(int(min),int(max))]
  elif '*' in i:
    a = [x for x in range(0,255)]
  else:
    a = [int(i)]
  addresses.append(a)
addresses = itertools.product(*addresses)

for i in addresses:
        print i

PS You need to add validation of input data and output as you need there..

J
JRazor, 2014-02-08
@JRazor

The head does not work after a working day, but in my opinion you can try something like this:

for num in range(0, 4):
    while b[num] <= e[num]:
        # yield
        b[num] += 1
        if b[num] <= e[num]:
            b[num + 1] = beggining[num + 1]

Most likely buggy code. Also questionable is the "simplification of the function".
And try to name variables more readably.

M
maxfox, 2014-02-09
@maxfox

It 's even better to use ipaddress or IPy if it's part of a project and not a script for personal use.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question