Shell中获取当前IP地址


参考地址

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}'

LC_ALL=C 英文输出
ifconfig 输出ip相关信息
# LC_ALL=C ifconfig
eth0      Link encap:Ethernet  HWaddr C2:AC:C3:E7:4A:33  
          inet addr:192.168.1.247  Bcast:0.0.0.0  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:84080 errors:0 dropped:80 overruns:0 frame:0
          TX packets:3595264 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:14627750 (13.9 MiB)  TX bytes:417627051 (398.2 MiB)
          Interrupt:27 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:127 errors:0 dropped:0 overruns:0 frame:0
          TX packets:127 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:18079 (17.6 KiB)  TX bytes:18079 (17.6 KiB)

 

grep 'inet addr:' 截取包含ip的那两行
# LC_ALL=C ifconfig|grep "inet addr:"
          inet addr:192.168.1.247  Bcast:0.0.0.0  Mask:255.255.255.0
          inet addr:127.0.0.1  Mask:255.0.0.0
 
 
grep -v '127.0.0.1' 去掉本地指向的那行
# LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"
          inet addr:192.168.1.247  Bcast:0.0.0.0  Mask:255.255.255.0 
cut -d: -f2 -d: 以:分割字符串 -f2:取第二组数据
# LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"|cut -d: -f2
192.168.1.247  Bcast
awk '{ print $1}' $1 表示默认以空格分割的第一组 同理 $@表示第二组
# LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"|cut -d: -f2|awk '{print $1}'
192.168.1.247
# LC_ALL=C ifconfig|grep "inet addr:"|grep -v "127.0.0.1"|cut -d: -f2|awk '{print $2}'
Bcast
 
 

 

 
 
 
 
 
 
 

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所在的列


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM