dtvpe4837413 2013-10-09 14:42
浏览 486
已采纳

正则表达式确定,如果给出IPv6或IPv4以及端口

I'm searching for a regular expression that can determine, if the given IP address is IPv4 or IPv6 and (most important for me) if a port number is attached, or not.

I tried a few regular expressions, but none of them worked as expected.

  • 写回答

1条回答 默认 最新

  • duanpai9945 2013-10-09 16:10
    关注

    If I can assume that the input will be a simple valid IP address and you simply want to know whether you have a port or not, you could do the following:

    if (preg_match("/^(?:[0-9.]+|(?:\[[0-9a-fA-F:]+\]))(:[0-9]+)$/", $ip)) 
    {
        echo "A port was found.";
    } 
    else 
    {
        echo "A port was not found.";
    }
    

    This will match an IP adress like

    • [2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:8080 or
    • 127.0.0.1:8080

    but it will not match

    • 2001:0db8:85a3:08d3:1319:8a2e:0370:7344 or
    • 127.0.0.1

    Keep in mind that the standard defines an IPv6 host to be distinguished by enclosing the IP literal within square brackets.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c