IP地址字符串操作问题

IP地址字符串操作问题

10.AB.C9我正在尝试从 5 位数字构建三个八位字节12ABC::

  • 12= 第一个八位位组
  • AB= 第二个八位位组
  • C= 第三个八位位组

我现有的代码有两种情况可能导致生成不正确的 IP。如果 C 有一个前导零,例如:02,那么第三个八位字节将为 027,并且 IP 不能有硬编码的前导零。

five_digits=12620

if [ "${five_digits:4:1}" -eq 0 ]; then
  ip_main="10.${five_digits:2:2}.9"
  gateway_ip_prefix="10.${five_digits:2:2}.2"

elif [ "${five_digits:4:1}" -ne 0 ]; then
  
  ip_main="10.${five_digits:2:2}.${five_digits:4:1}9"
  gateway_ip_prefix="10.${five_digits:2:2}.${five_digits:4:1}2"

上面的代码解决了C中的前导零问题

第二种情况是 A 为零,这意味着第二个八位字节将有一个前导零。我不确定如何处理这种情况,并希望使脚本更简单。

答案1

我会将每个八位位组分开,并删除每个八位位组中的任何前导零,然后将它们连接在一起。像这样的东西:

str="$five_digits"
if [[ ${#str} != 5 ]] || [[ ${str:0:2} != "12" ]]; then
    echo invalid input >&2;
    exit 1;
fi
a=10               # first octet, constant
b=${str:2:2}       # second octet
b=${b#0}           # remove one leading zero
c=${str:4:1}9      # third octet
c=${c#0}           # remove one leading zero

res="$a.$b.$c"     # concatenated result
echo "$res"

例如,将输入字符串12345变为10.34.59;1205510.5.59;并。1200010.0.9

相关内容