代码之家  ›  专栏  ›  技术社区  ›  Eric Platon

在shell脚本中获取IP地址的有效方法

  •  11
  • Eric Platon  · 技术社区  · 15 年前

    上下文: 在*nix系统上,可以通过以下方式以shell脚本获取机器的IP地址:

    ifconfig | grep 'inet' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}'
    

    或者这样:

    ifconfig | grep 'inet' | grep -v '127.0.0.1' | awk '{print $2}' | sed 's/addr://'
    

    问题: 有没有一种更直接、更可移植的方法来获取外壳脚本中使用的IP地址?

    ( my apologies to *BSD and Solaris users as the above command may not work 我无法测试)

    7 回复  |  直到 8 年前
        1
  •  12
  •   ghostdog74    15 年前

    你只需要一个awk命令就可以做到。不用用太多的管子。

    $ ifconfig | awk -F':' '/inet addr/&&!/127.0.0.1/{split($2,_," ");print _[1]}'
    
        2
  •  5
  •   coder    15 年前

    您提供了直接接口,从而减少了一个grep。

    ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'
    
        3
  •  2
  •   Community CDub    8 年前

    基于 this 可以使用以下命令

    ip route get 8.8.8.8 | awk 'NR==1 {print $NF}'
    
        4
  •  1
  •   t0mm13b    15 年前

    请看《北京指南》 networking 要使用简单的C程序获取套接字列表,请使用 getaddrinfo(...) 打电话。这个简单的C程序可以在shell脚本的一部分中使用,只需打印出可用于 stdout 这将更容易做到,然后依靠 ifconfig 如果您想保持可移植性作为 命令 可以变化。

    希望这有帮助, 最好的问候, 汤姆。

        5
  •  0
  •   David J Merritt    9 年前

    ifconfig grep'广播\ bcast'awk-f''打印$2'head-n 1 sed-e's/addr://g'

        6
  •  0
  •   Gautham Shervegar    9 年前

    也许这会有帮助。

     more /etc/hosts | grep `hostname` | awk '{print $1}'
    
        7
  •  0
  •   figtrap    8 年前
    # for bash/linux
    ipaddr(){
    if="${1:-eth0}"
    result=$(/sbin/ip -o -4 addr show dev "${if}" | sed 's/^.*inet // ; s/\/...*$//')
    printf %s "${result}"
    tty -s  && printf "\n"
    }