【问题标题】:How to find out your IP addresses using bash如何使用 bash 找出你的 IP 地址
【发布时间】:2016-03-07 04:19:35
【问题描述】:

我有一个有多个 IP 地址的服务器。我想在 bash 中计算出它们的确切值。我正在寻找类似的东西:

a=returnIpAddressStartingWith 10.60.12
b=returnIpAddressStartingWith 10.60.13

这样会返回:

> echo $a
10.60.12.23

在 linux 上是否有合理的方法可以做到这一点?

【问题讨论】:

    标签: linux bash centos ip


    【解决方案1】:

    您可以使用这样的函数进行搜索:

    findip() {
       ip -4 addr | awk -v ip="$1" -F '[/[:blank:]]+' '$2 == "inet" && index($3, ip){print $3}'
    }
    

    并通过以下方式查找 IP:

    a=$(findip '10.60.12')
    

    【讨论】:

      【解决方案2】:

      使用 grep/awk/cut 将其从“ip addr show”列表中解析出来,然后,如果您需要将其作为数组访问,则可以选择将您的列表复制到 Bash 数组中:

      # Create a string that is the list of all variables
      IPSTR=`ip addr show | fgrep 'inet ' | fgrep -v '127.0.0.1' | awk '{ print $2 }' | cut -d '/' -f 1`
      I=0
      for IP in $IPSTR ; do
          IPARY[$I]=$IP
          I=$(($I+1))
      done
      echo "First IP in array is ${IPARY[0]}"
      echo "Number of IP addresses in array is ${#IPARY[*]}"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-25
        • 2013-06-14
        • 2010-09-14
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 2019-11-14
        相关资源
        最近更新 更多