-1

Is there a way to validate if a route as below is valid or not with Python?

10.1.1.1 255.255.255.0 192.168.1.10
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
vaj oja
  • 1,151
  • 2
  • 16
  • 47

1 Answers1

1

Use RegEx to check it's IP address or not, and then you can use ipaddress module to check it's valid or not, for example:

import ipaddress
a = ['10.1.1.1', '255.255.255.0',
     '192.168.1.10', '999.999.999.999',
     '123.456.789', 'foobar', '123456']

for i in a:
    try:
        print()
        print(i)
        ipaddress.ip_address(i)
    except ValueError:
        print('invalid')
    else:
        print('valid')

Output:

10.1.1.1
valid

255.255.255.0
valid

192.168.1.10
valid

999.999.999.999
invalid

123.456.789
invalid

foobar
invalid

123456
invalid

Also, use ipaddress.IPv4Address() to check an IPv4 address, use ipaddress.IPv6Address to check an IPv6 address. Example:

>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')

>>> ipaddress.ip_address('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
IPv6Address('2001:db8:85a3::8a2e:370:7334')


>>> ipaddress.IPv4Address('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.5/ipaddress.py", line 1284, in __init__
    self._ip = self._ip_int_from_string(addr_str)
  File "/usr/lib/python3.5/ipaddress.py", line 1118, in _ip_int_from_string
    raise AddressValueError("Expected 4 octets in %r" % ip_str)
ipaddress.AddressValueError: Expected 4 octets in '2001:0db8:85a3:0000:0000:8a2e:0370:7334'

>>> ipaddress.IPv6Address('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
IPv6Address('2001:db8:85a3::8a2e:370:7334')


>>> ipaddress.IPv6Address('127.0.0.1')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.5/ipaddress.py", line 1909, in __init__
    self._ip = self._ip_int_from_string(addr_str)
  File "/usr/lib/python3.5/ipaddress.py", line 1646, in _ip_int_from_string
    raise AddressValueError(msg)
ipaddress.AddressValueError: At least 3 parts expected in '127.0.0.1'

>>> ipaddress.IPv4Address('127.0.0.1')
IPv4Address('127.0.0.1')
Community
  • 1
  • 1
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • 1
    I don't think that 255.255.255.0 is actually a valid address - it's part of a reserved range. But of course it depends on what exactly OP means by "valid". – interjay Nov 16 '15 at 10:13
  • @interjay: Yep, this question is little unclear. If this isn't OP's looking for I'll edit or delete it. – Remi Guan Nov 16 '15 at 10:15