PHP函数使用正则表达式验证IPv4和IPv6 [英] PHP function to validate IPv4 and IPv6 using regex

查看:355
本文介绍了PHP函数使用正则表达式验证IPv4和IPv6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为IPv4和v6创建一个函数,该函数也导致我使用本地ip.

I'm needing to create a function for IPv4 and v6 that I cause use local ip's as well.

我知道的是有效的IPv4范围从0.0.0.0到255.255.255.255 我对IPv6的了解是有限的,尽管它已经存在了一段时间,直到今天我才真正对其进行了很多研究.但是我想将来证明我正在做的功能,同时暂时保留它的复古性.我不确定IPv6的有效范围是多少.

What I know is a valid IPv4 ranges from 0.0.0.0 to 255.255.255.255 What I know of IPv6 is limited however as despite it being around for a while I haven't really looked much into it til today. But I want to future proof the function I am making a little bit while keeping it a bit retro for the time being. I'm not sure what the valid ranges are for IPv6.

无论如何,总的来说,我在想什么是一个函数

Anyway In general what I am thinking is a function to the extent of

function validateIP($ip, $vSix = NULL)
{
    if($vSix !== NULL)
    {
      if(preg_match([regex-to-validate-ipv6], $ip))
      {
        return true;
      }
      else
      {
        return false;
      }
    }

    if(preg_match([regex-to-validate-ipv4], $ip))
    {
      return true;
    }
    else
    {
      return false;
    }
}

我的事情是我对regex很烂,所以我不知道如何编写一个可以验证v4或6的代码.此外,对上述函数概念进行健全性检查也很好.

my thing is I suck with regex so I have no idea how to write one that will validate v4 or 6. Also a sanity check on the above function concept would be nice as well.

推荐答案

编辑

请参阅Natxet关于此答案的评论,以及Morgon的答案以寻求更好的解决方案.

Please see Natxet's comment on this answer, and Morgon's answer for a better solution.

原始答案

您可以只使用 inet_pton .如果IP不是有效的IPv6或IPv4,则返回false:

You can just use inet_pton. It returns false if the IP is not a valid IPv6 or IPv4:

function validateIP($ip){
    return inet_pton($ip) !== false;
}

这篇关于PHP函数使用正则表达式验证IPv4和IPv6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆