【问题标题】:ipv6 validation using regex使用正则表达式的 ipv6 验证
【发布时间】:2016-04-19 09:28:33
【问题描述】:
#!/bin/bash
echo "enter the ip address:"
read s
if [[ $s =~ ^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$ ]]; then

        echo -e '\E[47;31m'"\033[1mIPv6 Format\033[0m" 
        echo -n "The IPv6 Address Expanded Form:"
        EXPANDED=`sipcalc $s | fgrep Expand | cut -d '-' -f 2`
        echo -e "\033[32m $EXPANDED\033[0m"
        echo -n "IPv6 address Compress Form:"
        Compress=`sipcalc $s | fgrep Comp | cut -d '-' -f 2`
        echo  -e "\033[32m$Compress\033[0m"
        echo -n "Address Type of IPv6:"
        type=`sipcalc $s | fgrep type | cut -d '-'  -f 2,3,4`
        comment=`sipcalc $s | fgrep Comment | cut -d '-' -f 2`
        echo -e "\033[32m $type$comment\033[0m"
else
        echo  -e '\E[37;44m'"\033[1mNOT VALID IPv6 address\033[0m"
fi

大家好。我正在尝试使用此脚本验证 IPv6 地址。它运作良好。问题是它也接受像1111:2222:3333:4444:: 这样的IP。你能帮我避免这种类型的IP吗?

【问题讨论】:

标签: regex linux ipv6


【解决方案1】:

为什么不使用内置的 linux 实用程序,
ipcalc --ipv6 1111:2222:3333:4444::
如果它没有返回任何内容,那么您提供了正确的 IP
如果您提供不正确的IP,它会返回类似
ipcalc: bad IPv6 address:

希望对你有帮助。

【讨论】:

  • 我认为 OP 希望避免验证 IPv6 :: 速记
  • ipcalc 会支持 ipv6 地址吗?出现语法错误
  • 是的!对于 ipv4:ipcalc --ipv4,对于 ipv6:ipcalc --ipv6
  • ipcalc --ipv6 2001::af03::1001:0011 未知选项:--ipv6
  • 通过rpm -aq | grep initscripts检查你的initscripts的版本,它应该是版本9或更高版本支持ipv6
【解决方案2】:

这个正则表达式应该可以解决问题:

([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}

它匹配 8 个 1 到 4 个十六进制值的块,由 7 个 : 连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多