-5

I need to write a script that prints out a statement stating whether an IP is valid or invalid.

IP addresses are made up of four bytes (each with a valid range of 0-255).

valid examples: 127.0.0.1 , 123.244.100.1 , etc.

invalid examples: 124,44,2,2 , 127.0.2,4 , 355.23.24.43 , etc.

I'm guessing the easiest way would be to use regex? but i am having some trouble with that.

I also thought about using split(), but im not sure how I would handle any other special characters that aren't a "."

Any help or advice would be great, thanks

user2755244
  • 41
  • 4
  • 10

2 Answers2

3
>>> import socket
>>> socket.inet_aton("127.0.0.1")    # valid
'\x7f\x00\x00\x01'
>>> socket.inet_aton("127.1")        # oh yes this is valid too!
'\x7f\x00\x00\x01'
>>> socket.inet_aton("127.0.0,1")    # this isn't
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

to test for valid IPv6 addresses you can use

>>> socket.inet_pton(socket.AF_INET6, "2001:db8:1234::")
b' \x01\r\xb8\x124\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

You could use the IPy module which specialises in handling IP addresses. https://pypi.python.org/pypi/IPy/

from IPy import IP
try:
    ip = IP('127.0.0.1')
except ValueError:
    # invalid IP

Python 3 offers the ipaddress module. http://docs.python.org/3/library/ipaddress. Instead of using IPy, you can do this:

ip = ipaddress.ip_address('127.0.0.1')

and that will throw a ValueError exception.

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
russellc
  • 494
  • 3
  • 7