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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题