在终端中输入ifconfig可以看到很多的信息,其中包含了本机的ip,但是信息过多,即使你知道从什么地方查找,每次看也会头晕,我们需要精确找到本机ip的方法。
在linux中使用命令
1 2 3 4 5 6 7 8
| $ ifconfig eth0 eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.8.21 netmask 255.255.240.0 broadcast 192.168.8.1 ether 00:16:3e:0c:ec:20 txqueuelen 1000 (Ethernet) RX packets 215013189 bytes 59080762287 (55.0 GiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 125960779 bytes 124345275246 (115.8 GiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
|
第二行的第一个ip就是本机ip192.168.8.21
在MacOS中稍有不同,命令为
接下来,我们使用grep awk来进行精确获取
CentOS
1
| $ ifconfig eth0 | grep inet | grep -v inet6 | awk '{print $2}'
|
Ubuntu
1
| $ ifconfig eth0 | grep inet | grep -v inet6 | awk '{print $2}' | awk -v FS=":" '{print $2}'
|
MacOS
1
| $ ifconfig en0 | grep inet | grep -v inet6 | awk '{print $2}'
|