You can use the PHP code below to check if an IP address is valid or not.

I needed this when building a form that accepted IP addresses as input for a network monitoring tool. Rather than writing a regex to match the IP format, PHP’s built-in filter_var with FILTER_VALIDATE_IP handles both IPv4 and IPv6 validation out of the box.

You can also pass additional flags like FILTER_FLAG_NO_PRIV_RANGE to reject private IPs (192.168.x.x, 10.x.x.x) or FILTER_FLAG_NO_RES_RANGE to reject reserved ranges. This is useful when you only want to accept public-facing addresses.

$ip = ""; //enter a valid or invalid ip address here
if(filter_var($ip, FILTER_VALIDATE_IP)) {
  // The IP Address is valid
} else {
  // The IP Address is not valid
}

Wasn’t that easy!?!