1

Given input is 192.168.3.78/27

Input can be any Class C ip address, The above ip is tried for example

expected output should display all the ips from 192.168.3.65 to 192.168.3.94 as below

192.168.3.65
192.168.3.66
192.168.3.67
...
...
192.168.3.94
>>> for x in ipaddress.ip_network('192.168.3.78/27'):
     print(x)
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    for x in ipaddress.ip_network('192.168.3.78/27'):
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\ipaddress.py", line 74, in ip_network
    return IPv4Network(address, strict)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\ipaddress.py", line 1536, in __init__
    raise ValueError('%s has host bits set' % self)
ValueError: 192.168.3.78/27 has host bits set
glibdud
  • 7,550
  • 4
  • 27
  • 37
kavi Raj
  • 211
  • 2
  • 10
  • how to format the the problem statement ..am facing difficult to understand the formatting part – kavi Raj May 16 '19 at 15:37
  • Possible duplicate of [Python 3: create a list of possible ip addresses from a CIDR notation](https://stackoverflow.com/questions/1942160/python-3-create-a-list-of-possible-ip-addresses-from-a-cidr-notation) – rdas May 16 '19 at 15:43
  • Its not duplicate as i tried in the above link but not usefull – kavi Raj May 16 '19 at 15:55

1 Answers1

1

Interface objects can accept an arbitrary host address and give you the corresponding network:

for x in ipaddress.ip_interface('192.168.3.78/27').network:
    print(x)

Result:

192.168.3.64
192.168.3.65
...
192.168.3.94
192.168.3.95
glibdud
  • 7,550
  • 4
  • 27
  • 37
  • glibdud the above looks good... thanks.. any other logic based is possible without the ipaddress module? – kavi Raj May 16 '19 at 15:54
  • @kaviRaj Well sure, you could parse the octets and netmask and calculate it yourself. Not sure why you'd want to when there's a simpler way to do it within the standard library. – glibdud May 16 '19 at 17:42
  • I totally agree with you when we have simplest way why we need to the logic based or long methods as i observed some people expects us to know the complex solution just to see how we think or try to resolve an issue , or how we think on logic way during an interview process. :) – kavi Raj May 16 '19 at 18:06