-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

4
  • 5
    Since when is 123.444.333.1 a valid IP? Commented Nov 22, 2013 at 6:02
  • 1
    Looking forward to your regex for ipv6 addresses...why not use a library? Commented Nov 22, 2013 at 6:05
  • stackoverflow.com/questions/319279/… Commented Nov 22, 2013 at 6:05
  • 2
    2003::5 is a valid IP address. Commented Nov 22, 2013 at 6:05

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.