DEV Community

Cover image for The IPv4 address validation algorithm
Leandre
Leandre

Posted on

The IPv4 address validation algorithm

Introduction

We are implementing an IPv4 validation algorithm to check whether a string input is a valid IPv4 address.

What is an IPv4 Address

IPv4 addresses are usually represented in dot-decimal notation, consisting of four decimal numbers, each ranging from 0 to 255, separated by dots(.). Each part represents a group of 8 bits (an octet) of the address.
Example: 172.16.254.1

Implementation

IPv4 has 4 parts that are separated by a dot(.). Each part is a numerical value ranging from 0 to 255.
We don't care about the IP address classes, we only care about a valid IPv4 address

Here is our solution implemented in JavaScript:

function validateIpAddress(ipaddress) {
    if (!ipaddress) return false;

    const ipArray = ipaddress.split('.');
    if (!Array.isArray(ipArray) || ipArray.length !== 4) return false;

    const invalidIPArray = ipArray.filter((octet) => {
        const number = parseInt(octet);
        return isNaN(number) || number < 0 || number > 255;
    });

    if (invalidIPArray.length) return `Wrong octet: ${invalidIPArray}`;

    return true;
}
Enter fullscreen mode Exit fullscreen mode

Breakdown

Step 1: In algorithms, it's always the best approach to check for falsy values to eliminate unwanted errors.

Step 2: Let's split the string argument by dot(.) using split function which returns an array.

Step 3: We check the array length as it must be composed of 4 parts. If the array length different from 4, you guessed it!! It's invalid.

Step 4: Filter the array filter function performing these 2 important tasks:

  1. Parse array value to an integer value
  2. Check and return the value that is not ranging between 0-255, or if the value failed while converting to an integer that returns NaN.

Step 5: Check the returned filtered array length, if the length is not 0, you guessed it!! it's an invalid IP. We return the invalid parts of the given IP address.

filter() method creates an array filled with all array elements that pass a test/condition specified
split() method is used to split a string into an array of substrings and returns the new array.

Conclusion

Feel free to contribute and improve this approach.
Thank you for reading the blog post. Subscribe for more articles
Contributor: Deogratias
Repo

Top comments (0)