php 如何检查用户输入的 IP 地址是否有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6211148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:39:59  来源:igfitidea点击:

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

phpvalidationip

提问by Sanjay dev

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.

我想检查输入的输入是否是有效的 IP 地址。我想要一个特定的功能来帮助我验证用户输入。

回答by deceze

回答by chiborg

// 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.

您可以通过过滤 IPv4 和 IPv6 IP 地址并排除私有和保留 IP 来修改此设置。

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

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

回答by Aniket Singh

By using preg_match();

通过使用 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);
}