21. isIPv4Address


Task

An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.

IPv4 address is a string with the following structure: a.b.c.d, where a, b, c and d are integers in range [0, 255]. For example, 0.0.0.0, 255.255.255.255 or 252.0.128.32 are correct IPv4 addresses, and 0.0.0.256, -1.1.1.1, 0.0.0.0.0 are incorrect.

a.b is named network part and c.d is named host part.

Given a string, find out if it satisfies the IPv4 address naming rules.

Example

  • For inputString = "172.16.254.1", the output should be
    isIPv4Address(inputString) = true;

  • For inputString = "172.316.254.1", the output should be
    isIPv4Address(inputString) = false.
    316 is not in range [0, 255].

  • For inputString = ".254.255.0", the output should be
    isIPv4Address(inputString) = false.
    There is no first number.

Input/Output

  • [execution time limit]
    4 seconds (py3)

  • [input] string inputString
    A string consisting of digits, full stops and lowercase English letters.
    Guaranteed constraints: 1 ≤ inputString.length ≤ 30.

  • [output] boolean
    true if inputString satisfies the IPv4 address naming rules, false otherwise.

My Solution

def isIPv4Address(inputString):
    try:
        address = list(map(int, inputString.split('.')))
        if len(address) != 4:
            return False
        for number in address:
            if (number < 0) or (number > 255):
                return False
        return True
    except:
        return False