PHP 5.2.0之后有专用函数
转自:脚本之家

1、合法IP

if(filter_var($ip, FILTER_VALIDATE_IP)) {
// it's valid
} else {
// it's not valid
}

2、合法IPv4

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
// it's valid
} else {
// it's not valid
}

3、合法公共IPv4(排除私有IP)

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) {
// it's valid
} else {
// it's not valid
}

4、合法IPv6

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
// it's valid
} else {
// it's not valid
}

5、合法公共IPv4或公共IPv6(排除私有IP)

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
// it's valid
} else {
// it's not valid
}