How do I check if a users input is a valid IP address or not?

后端 未结 3 604
囚心锁ツ
囚心锁ツ 2020-12-14 18:41

I want to check if an entered input is a valid IP address or not. I would like a specific function that will help me validate a users input.

相关标签:
3条回答
  • 2020-12-14 18:57

    By using preg_match();

    function checkIPAddress($ipAddress) 
    {
        return preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ipAddress);
    }
    
    0 讨论(0)
  • 2020-12-14 19:05
    filter_var($ip, FILTER_VALIDATE_IP)
    

    http://www.php.net/filter_var

    0 讨论(0)
  • 2020-12-14 19:07

    // Usually you'd get the value from $_POST or $_GET
    $ip = "10.3.1.5";
    if(!filter_var($ip, FILTER_VALIDATE_IP)) {
       echo "Not a valid IP address!";
    }
    

    You can modify this by filtering for IPv4 and IPv6 IP addresses and exclude private and reserved IPs.

    http://www.php.net/manual/filter.filters.validate.php

    0 讨论(0)
提交回复
热议问题