Search code examples
phpregexipv6ipv4

Regex to determine, if IPv6 or IPv4 and if port is given


I'm searching for a regular expression that can determine, if the given IP address is IPv4 or IPv6 and (most important for me) if a port number is attached, or not.

I tried a few regular expressions, but none of them worked as expected.


Solution

  • If I can assume that the input will be a simple valid IP address and you simply want to know whether you have a port or not, you could do the following:

    if (preg_match("/^(?:[0-9.]+|(?:\[[0-9a-fA-F:]+\]))(:[0-9]+)$/", $ip)) 
    {
        echo "A port was found.";
    } 
    else 
    {
        echo "A port was not found.";
    }
    

    This will match an IP adress like

    • [2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:8080 or
    • 127.0.0.1:8080

    but it will not match

    • 2001:0db8:85a3:08d3:1319:8a2e:0370:7344 or
    • 127.0.0.1

    Keep in mind that the standard defines an IPv6 host to be distinguished by enclosing the IP literal within square brackets.