Skip to content

Is IPv4 Address?

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.

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

Example

  • For inputString = "172.16.254.1", the output should be

    is_ipv4_address(inputString) = true
  • For inputString = "172.316.254.1", the output should be

    is_ipv4_address(inputString) = false

    316 is not in range [0, 255].

  • For inputString = ".254.255.0", the output should be

    is_ipv4_address(inputString) = false

    There is no first number.

Solution

py
import ipaddress


def is_ipv4_address(inputString):
    try:
        ipaddress.ip_address(inputString)
        return True
    except ValueError:
        return False


print(is_ipv4_address("234.3.123.123"))
js
// Input:
// inputString: "1.1.1.1a"
// Expected Output:
// false
function is_ipv4_address(inputString) {
  const parts = inputString.split('.');
  if (parts.length !== 4) {
    return false;
  }
  for (let i = 0; i < parts.length; i++) {
    const part = parts[i];
    if (part.length === 0) {
      return false;
    }
    if (part.length > 1 && part[0] === '0') {
      return false;
    }
    if (part.length > 3) {
      return false;
    }
    const num = Number(part);
    if (isNaN(num)) {
      return false;
    }
    if (num < 0 || num > 255) {
      return false;
    }
  }
  return true;
}

console.log(is_ipv4_address('234.3.123.123'));

my thoughts are neither my employer's nor my wife's