Skip to content Skip to sidebar Skip to footer

Regular Expressions In Python For Dissecting Ip

I am currently trying to script a task for my Bind9 server. The goal is to have the user input an IP address in the following format: 192.168.90.150 I would then like Python to ta

Solution 1:

Validation: How to validate IP address in Python?

+plus

first, second, third, fourth = str(ipaddy).split('.')

Solution 2:

If you are reasonably sure the input is going to be an IPv4 in dotted form, you don't even need a regular expression:

assert possible_ip.count(".") ==3
ip_parts = possible_ip.split(".")
ip_parts = [int(part) for part in ip_parts]
first, second, third, fourth = ip_parts

Solution 3:

You can just use the builtin str functions.

try:
    first, second, third, fourth = [int(s) for s in some_text.split('.')]
except ValueError as e:
    print'Not 4 integers delimited by .'ifnotall (0 <= i <= 254for i in (first, second, third, fourth)):
    print'Syntax valid, but out of range value: {} in "{}"'.format(i, some_text)

Solution 4:

Make a list of bytes:

>>> [ byteforbytein'192.168.90.150'.split('.') ]
['192', '168', '90', '150']

Solution 5:

defvalidate_and_split_ip(ip):
    parts = ip.split('.')
    iflen(parts) != 4:
        returnNonefor part in parts:
        ifnot part.isdigit() ornot0<=int(part)<=255:
            returnNonereturn [int(part) for part in parts]

Test:

>>>validate_and_split_ip('123.123.0.255')
[123, 123, 0, 255]
>>>validate_and_split_ip('123.123.0.256') # Returns None>>>validate_and_split_ip('123.123.123.a') # Returns None

You then have a list rather than 4 variables, which is more Pythonic and cleaner.

Post a Comment for "Regular Expressions In Python For Dissecting Ip"