IP Address Validation

  • + 0 comments

    PHP Solution:

    <?php
        $input = stream_get_contents($_fp);
        $lines = preg_split('/\R/', $input, -1, PREG_SPLIT_NO_EMPTY);
        array_shift($lines);
        $ipv4_pattern = '/^(([01]?[0-9]{0,2}|2[0-5]?[0-5]?)\.){3}([01]?[0-9]{0,2}|2[0-5]?[0-5]?)$/';
        $ipv6_pattern = '/^(([a-fA-F0-9]{1,4}):){7}[a-fA-F0-9]{1,4}$/';
        foreach($lines as $line) {
            $result = 'Neither';
            if (preg_match($ipv4_pattern, $line)) {
                $result = 'IPv4';
            } elseif (preg_match($ipv6_pattern, $line)) {
                $result = 'IPv6';
            }
            
            echo $result . PHP_EOL;
        }