Shell中获取当前IP地址

本文转载自: https://www.cnblogs.com/wangkangluo1/archive/2012/04/13/2446163.html 作者:wangkangluo1 转载请注明该声明。

参考地址

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值