0

Below input file has:

 ipnetwork:111.0.1.0/255.255.255.0

I am reading this input file using python dictionary like below.

d = {}
with open('inputfile.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value
 for key, value in  d.iteritems():
     if key == 'ipnetwork':
        ip = value

Now I need help here to validate the input provided that is.

ipnetwork must be below format like below:

 1.2.2.0/255.255.0.0--valid input
 111.111.111.0/255.0.0.0 --valid input
 256.500.111.0/0.0.0.0 --not valid input since ip does not contain more than 255 number
 10.10.aa.1/255.255.255.0 --not valid input since ip address does not contain alphabets
Bittu
  • 31
  • 2
  • 9
  • 1
    Possible duplicate of [check if a string matches an IP address pattern in python?](https://stackoverflow.com/questions/3462784/check-if-a-string-matches-an-ip-address-pattern-in-python) – idjaw Jun 22 '17 at 01:47

1 Answers1

0

I got solution using netaddr module for this. Just want to post here test results.

 I got below netaddr tool it will validate above. below is the tested results

>>> from netaddr import *
>>> ip = IPNetwork('1.1.1.0')
>>> ip = IPNetwork('1.1.1.0/255.255.255.0')
>>> ip = IPNetwork('1.1.1.0/255.255.256.0')
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\netaddr\ip\__init__.py", line 938, in 
  __init__
   raise AddrFormatError('invalid IPNetwork %s' % addr)
  netaddr.core.AddrFormatError: invalid IPNetwork 1.1.1.0/255.255.256.0
  >>> ip = IPNetwork('1.a.1.0/255.255.255.0')
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\netaddr\ip\__init__.py", line 938, in 
 __init__
  raise AddrFormatError('invalid IPNetwork %s' % addr)
  netaddr.core.AddrFormatError: invalid IPNetwork 1.a.1.0/255.255.255.0
Bittu
  • 31
  • 2
  • 9