当我执行该命令时,ip address show
我的服务器显示了我为其分配的数百个 IPv6。它运行良好,但是 IP 地址的前导零和尾随零被省略,如下所示:
3600:3c00:e000:92b::5/64
我需要以完整形式显示 IP,例如:
3600:3c00:e000:092b:0000:0005/64
因为稍后我会将结果匹配ip address show
到正则表达式中以从列表中检查地址,并且所有地址都采用“完整形式”。
你知道我该如何修复这个问题吗?
答案1
以下 bash 脚本将以扩展形式和 /proc/net/tcp6 格式打印 IPv6(如果不需要,可以删除最后一个回显):
#!/bin/bash
# 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)
}
# print ipv6 in linux /proc/net/tcp6 format
ipv6ToNetTcp6() {
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
word1="0x$1"
word2="0x$2"
word3="0x$3"
word4="0x$4"
word5="0x$5"
word6="0x$6"
word7="0x$7"
word8="0x$8"
printf "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n" \
$((word2 & 0xFF)) \
$((word2 >> 8)) \
$((word1 & 0xFF)) \
$((word1 >> 8)) \
$((word4 & 0xFF)) \
$((word4 >> 8)) \
$((word3 & 0xFF)) \
$((word3 >> 8)) \
$((word6 & 0xFF)) \
$((word6 >> 8)) \
$((word5 & 0xFF)) \
$((word5 >> 8)) \
$((word8 & 0xFF)) \
$((word8 >> 8)) \
$((word7 & 0xFF)) \
$((word7 >> 8))
}
result=$(expand_ipv6 $1)
echo $result
result2=$(ipv6ToNetTcp6 $1)
echo $result2
exit 0
例如,授予其执行权限后:
# ./fullip6 "3600:3c00:e000:92b::5/64"
3600:3c00:e000:092b:0000:0000:0000:0005
003C00362B0900E00000000005000000