IP Address Validation Without Regular Expressions

Validating an IP address is pretty simple, but requires an obnoxious regular expression in order to account for the possible values. Most examples I’ve seen resort to a regular expression to solve the task, but using a simple [0-9]{1,3} pattern isn’t enough. For example, it won’t prevent an IP like 444.555.666.777 from getting past the filter, so it has to be a little more complex:

((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])

Expressions like this suck, so I decided to go about writing my own function to validate an IPv4 address. In Python, it can be done in one line:

  1. is_valid = (ip.count('.') == 3 and False if False in [int(i) in range(0,256) for i in ip.split('.')] else True)

This statement starts with counting the occurrences of the ‘.’ character  in the `ip` variable (string). The interpreter will halt here if the number of octets is incorrect, preventing iteration over clearly-invalid IPv4 addresses like “192.168.1” or “192.168..1.1”. The second half of the statement uses a generator to determine if each octet is a number between 0 and 255 (inclusive), resulting in a list of boolean values. If False is in this list, the statement will evaluate to False.

Timeit shows this function is ever-so-slightly slower than compiling the above regular expression. The regular expression takes between 0.000015 – 0.000025s while the function has been consistently around 0.000025s.

Another variant of the function (using a similar methodology) in PHP looks like this:

  1. function validate_ip($ip) {
  2.     $i = 0;
  3.     foreach(explode('.', $ip) as $part) {
  4.         if ((int)$part >= 0 && (int)$part < 256) {
  5.             $i++;
  6.         }
  7.     }
  8.     return ($i === 4);
  9. }

While newer versions of PHP support generators, this function was written for an older version, hence the difference in formatting. Unfortunately, I don’t have any benchmarks for this function.

 

IP Address Validation Without Regular Expressions

Leave a Reply