Shell中获取当前IP地址

出自Linux Wiki

在2008年6月24日 (二) 03:19由Chenxing (讨论 | 贡献)所做的修订版本
(差异) ←上一修订 | 最新修订 (差异) | 下一修订→ (差异)

ifconfig返回的信息中包括IP地址,但要在Shell中获取当前IP地址,则要麻烦一些

获取方法

由于不同系统中ifconfig返回信息的格式有一定差别,故分开讨论:[1]

Linux:

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

FreeBSD/OpenBSD:

ifconfig  | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' |
awk '{ print $2}'

Solaris:

ifconfig -a | grep inet | grep -v '127.0.0.1' |
awk '{ print $2}'

三段代码的原理类似,都是先获取含有IP的行,再去掉含有127.0.0.1的行。最后获取IP所在的列

样例代码

下面是一则示例的代码[2]

#!/bin/sh
# Shell script scripts to read ip address
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
# Get OS name
OS=`uname`
IO="" # store IP
case $OS in
   Linux) IP=`ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`;;
   FreeBSD|OpenBSD) IP=`ifconfig  | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk '{ print $2}'` ;;
   SunOS) IP=`ifconfig -a | grep inet | grep -v '127.0.0.1' | awk '{ print $2} '` ;;
   *) IP="Unknown";;
esac
echo "$IP"

代码出处

  1. http://www.cyberciti.biz/tips/read-unixlinux-system-ip-address-in-a-shell-script.html
  2. http://bash.cyberciti.biz/misc-shell/read-local-ip-address/
个人工具
简体繁体转换