我想基于给定的IPv6地址更新djbdns(dbndns)配置文件,例如: 2a01:488:66:1000:523:f116:0:1
或::1
。
dbndns需要扩展的IPv6地址,例如2a010488006610000523f11600000001
的{{1}}。
扩展此类IPv6地址的最简单方法是什么?
答案 0 :(得分:5)
使用sipcalc
可能会这样做。它提供的信息比您需要的多,但有点grep
和cut
可以解决这个问题: - )
$ EXPANDED=`sipcalc 2001::1 | fgrep Expanded | cut -d '-' -f 2`
$ echo $EXPAND
2001:0000:0000:0000:0000:0000:0000:0001
供参考,这是sipcalc
的完整输出:
$ sipcalc 2001::1
-[ipv6 : 2001::1] - 0
[IPV6 INFO]
Expanded Address - 2001:0000:0000:0000:0000:0000:0000:0001
Compressed address - 2001::1
Subnet prefix (masked) - 2001:0:0:0:0:0:0:1/128
Address ID (masked) - 0:0:0:0:0:0:0:0/128
Prefix address - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
Prefix length - 128
Address type - Aggregatable Global Unicast Addresses
Network range - 2001:0000:0000:0000:0000:0000:0000:0001 -
2001:0000:0000:0000:0000:0000:0000:0001
答案 1 :(得分:2)
我最近想要一种可以跨shell移植并在openwrt等平台上工作的无依赖解决方案。我想出了以下片段:
# helper to convert hex to dec (portable version)
hex2dec(){
[ "$1" != "" ] && printf "%d" "$(( 0x$1 ))"
}
# expand an ipv6 address
expand_ipv6() {
ip=$1
# prepend 0 if we start with :
echo $ip | grep -qs "^:" && ip="0${ip}"
# expand ::
if echo $ip | grep -qs "::"; then
colons=$(echo $ip | sed 's/[^:]//g')
missing=$(echo ":::::::::" | sed "s/$colons//")
expanded=$(echo $missing | sed 's/:/:0/g')
ip=$(echo $ip | sed "s/::/$expanded/")
fi
blocks=$(echo $ip | grep -o "[0-9a-f]\+")
set $blocks
printf "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n" \
$(hex2dec $1) \
$(hex2dec $2) \
$(hex2dec $3) \
$(hex2dec $4) \
$(hex2dec $5) \
$(hex2dec $6) \
$(hex2dec $7) \
$(hex2dec $8)
}
我也有这个功能来压缩
# returns a compressed ipv6 address under the form recommended by RFC5952
compress_ipv6() {
ip=$1
blocks=$(echo $ip | grep -o "[0-9a-f]\+")
set $blocks
# compress leading zeros
ip=$(printf "%x:%x:%x:%x:%x:%x:%x:%x\n" \
$(hex2dec $1) \
$(hex2dec $2) \
$(hex2dec $3) \
$(hex2dec $4) \
$(hex2dec $5) \
$(hex2dec $6) \
$(hex2dec $7) \
$(hex2dec $8)
)
# prepend : for easier matching
ip=:$ip
# :: must compress the longest chain
for pattern in :0:0:0:0:0:0:0:0 \
:0:0:0:0:0:0:0 \
:0:0:0:0:0:0 \
:0:0:0:0:0 \
:0:0:0:0 \
:0:0; do
if echo $ip | grep -qs $pattern; then
ip=$(echo $ip | sed "s/$pattern/::/")
# if the substitution occured before the end, we have :::
ip=$(echo $ip | sed 's/:::/::/')
break # only one substitution
fi
done
# remove prepending : if necessary
echo $ip | grep -qs "^:[^:]" && ip=$(echo $ip | sed 's/://')
echo $ip
}
您可以将它们组合起来测试给定输入是否为ipv6
# a valid ipv6 is either the expanded form or the compressed one
is_ipv6(){
expanded="$(expand_ipv6 $1)"
[ "$1" = "$expanded" ] && return 0
compressed="$(compress_ipv6 $expanded)"
[ "$1" = "$compressed" ] && return 0
return 1
}
我希望这有帮助!这些片段取自https://github.com/chmduquesne/wg-ip。如果您发现任何错误,请提供帮助!
答案 2 :(得分:0)
这对你好吗?
kent$ echo "2a01:488:66:1000:523:f116:0:1"|awk -F: '{for(i=1;i<=NF;i++)x=x""sprintf ("%4s", $i);gsub(/ /,"0",x);print x}'
2a010488006610000523f11600000001