I use PHP in my work to judge the IP of the internal and external networks, and I stumbled upon a ready-made implementation function when I searched for information. Cool!
filter_var ($ ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
The function can also validate url, email, etc.