Validate IPv6 Address

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • prabhuram.k@gmail.com

    #1

    Validate IPv6 Address

    Can anybody know how to validate IPV4 and IPV6 address in PHP. I am
    using PHP 4.2.3 for some compatiability reason.

  • Juliette

    #2
    Re: Validate IPv6 Address

    prabhuram.k@gma il.com wrote:[color=blue]
    > Can anybody know how to validate IPV4 and IPV6 address in PHP. I am
    > using PHP 4.2.3 for some compatiability reason.
    >[/color]


    // Regex by Daniel Adam
    // http://www.regxlib.com/REDetails.aspx?regexp_id=1139
    $pattern[ipv4] =
    '/^((\d|[1-9]\d|2[0-4]\d|25[0-5]|1\d\d)(?:\.(\d |[1-9]\d|2[0-4]\d|25[0-5]|1\d\d)){3})$/';

    // Checks whether a given IPv6 address string could be valid based on
    full and compressed IPv6 addresses as defined in RFC 2373 -
    http://www.faqs.org/rfcs/rfc2373.html
    // Regex by Jeff Johnson
    // http://www.regxlib.com/REDetails.aspx?regexp_id=1000
    $pattern[ipv6] =
    '/^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b( (25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\ b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\ b))|(([0-9A-Fa-f]{1,4}:){0,5}:(( \b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\ b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\ b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\ b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\ b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\ b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)) $/';


    Pass the value to be tested to the below as $value:

    $valid_ipv4 = preg_match( $pattern[ipv4], $value ) ? TRUE : FALSE;

    $valid_ipv6 = preg_match( $pattern[ipv6], $value ) ? TRUE : FALSE;


    Good luck,
    Juliette

    Comment

    • bobzimuta

      #3
      Re: Validate IPv6 Address

      why not combine the two ip functions ip2long and long2ip:

      from http://us2.php.net/manual/en/function.ip2long.php

      <?php
      // make sure IPs are valid. also converts a non-complete IP into
      // a proper dotted quad as explained below.
      $ip = long2ip(ip2long ("127.0.0.1" )); // "127.0.0.1"
      $ip = long2ip(ip2long ("10.0.0")); // "10.0.0.0"
      $ip = long2ip(ip2long ("10.0.256") ); // "10.0.1.0"
      ?>

      Comment

      Working...