Shell中獲取當前IP地址

此頁由 ngU khO 於 2008年10月29日 (星期三) 09:44 的最後更改。 在Linux Wiki用戶Chenxing的工作基礎上。

出自Linux Wiki

提示:此文已超过 15 年(5629 天)未更新,如发现内容过时或有误,欢迎改进:)

ifconfig返回的信息中包括IP地址,但要在Shell中獲取當前IP地址,則要麻煩一些

獲取方法

由於不同系統中ifconfig返回信息的格式有一定差別,故分開討論:[1]

Linux:

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

FreeBSD/OpenBSD:

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

Solaris:

LC_ALL=C 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/

本文对您有帮助?分享给更多朋友!

反馈与讨论

发现文档不全面、有错误却没时间编辑文档?想分享自己的经验或见解?欢迎在此留言、讨论。
简体繁体转换