-7

Note! I can not use filter_var in my application. Only generic functions. Perhaps a regex?

<?php
  if (is_valid_ipv4($ip)) { ... }
  else if (is_valid_ipv6($ip) { ... }
  else { ... }
?>
Lex Podgorny
  • 2,598
  • 1
  • 23
  • 40
  • 2
    Look into [`filter_var()`](http://php.net/manual/en/function.filter-var.php) and the [`FILTER_VALIDATE_IP`](http://php.net/manual/en/filter.filters.validate.php) filter. – MonkeyZeus Apr 05 '18 at 19:20
  • 2
    What exactly is your definition of "generic functions"? – Patrick Q Apr 05 '18 at 19:22
  • 3
    Why not filter_var()? It's core PHP, difficult to get more generic than that – Mark Baker Apr 05 '18 at 19:23
  • A regex could be like: https://stackoverflow.com/questions/23483855/javascript-regex-to-validate-ipv4-and-ipv6-address-no-hostnames – marcel.js Apr 05 '18 at 19:23
  • @MonkeyZeus Please try reading the question. – Lex Podgorny Apr 05 '18 at 19:58
  • @MarkBaker Unfortunately, in the environment where I work this function is disabled. Don't ask why. – Lex Podgorny Apr 05 '18 at 20:01
  • I spent as much time reading your question as you did researching your problem. Googling "validate ipv4 with regex" and "validate ipv6 with regex" returns several results so since you make no mention of trying anything at all, don't expect top-notch effort from people coming across your post. – MonkeyZeus Apr 06 '18 at 12:09
  • Anyways, check out https://stackoverflow.com/q/53497/2191572 – MonkeyZeus Apr 06 '18 at 12:11

1 Answers1

8

You can just use inet_pton. It returns false if the IP is not a valid IPv6 or IPv4:

function validateIP($ip){
    return inet_pton($ip) !== false;
}
Khaled Alam
  • 885
  • 7
  • 12
  • 1
    plus 1 for teaching me something new – MonkeyZeus Apr 05 '18 at 19:22
  • 2
    Careful, though: `inet_pton()` also throws `E_WARNING` along with returning `false` if the supplied value is not valid – ishegg Apr 05 '18 at 19:26
  • @ishegg I was just about to comment the same thing about `E_WARNING` but I think that returning `false` is not totally unexpected for PHP. – MonkeyZeus Apr 05 '18 at 19:28
  • Certainly an interesting option, but the question then is, what is the complexity / performance of the underlying code of this function vs `filter_var()`? – Patrick Q Apr 05 '18 at 19:31
  • @MonkeyZeus [the lastest PHP7 alpha (7.3.0alpha1)](https://github.com/php/php-src/blob/master/NEWS) suppresses the warning (just now found out when researching this) – ishegg Apr 05 '18 at 19:33
  • @ishegg Interesting. Unfortunately people are still rocking PHP 5.x like it's 2005 still so I think suppressing it with `@inet_pton()` would be a useful option. – MonkeyZeus Apr 06 '18 at 11:44