Which terminal command to get just IP address and

2019-01-29 19:33发布

I'm trying to use just the IP address (inet) as a parameter in a script I wrote.

Is there an easy way in a unix terminal to get just the IP address, rather than looking through ifconfig?

21条回答
smile是对你的礼貌
2楼-- · 2019-01-29 20:15

I wanted something simple that worked as a Bash alias. I found that hostname -I works best for me (hostname v3.15). hostname -i returns the loopback IP, for some reason, but hostname -I gives me the correct IP for wlan0, and without having to pipe output through grep or awk. A drawback is that hostname -I will output all IPs, if you have more than one.

查看更多
走好不送
3楼-- · 2019-01-29 20:16

use this one line script: ifconfig | grep "inet " | grep -v 127.0.0.1|awk 'match($0, /([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/) {print substr($0,RSTART,RLENGTH)}' mac & linux (tested in ubuntu) both works.

查看更多
做个烂人
4楼-- · 2019-01-29 20:19

This will give you all IPv4 interfaces, including the loopback 127.0.0.1:

ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

This will only show eth0:

ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

And this way you can get IPv6 addresses:

ip -6 addr | grep -oP '(?<=inet6\s)[\da-f:]+'

Only eth0 IPv6:

ip -6 addr show eth0 | grep -oP '(?<=inet6\s)[\da-f:]+'
查看更多
冷血范
5楼-- · 2019-01-29 20:23

Command ifconfig is deprected and you should use ip command on Linux.

Also ip a will give you scope on the same line as IP so it's easier to use.

This command will show you your global (external) IP:

ip a | grep "scope global" | grep -Po '(?<=inet )[\d.]+'

All IPv4 (also 127.0.0.1):

ip a | grep "scope" | grep -Po '(?<=inet )[\d.]+'

All IPv6 (also ::1):

ip a | grep "scope" | grep -Po '(?<=inet6 )[\da-z:]+'
查看更多
别忘想泡老子
6楼-- · 2019-01-29 20:23

That would do the trick in a Mac :

ping $(ifconfig en0 | awk '$1 == "inet" {print $2}')

That resolved to ping 192.168.1.2 in my machine.

Pro tip: $(...) means run whatever is inside the parentheses in a subshell and return that as the value.

查看更多
再贱就再见
7楼-- · 2019-01-29 20:23
ip addr|awk '/eth0/ && /inet/ {gsub(/\/[0-9][0-9]/,""); print $2}'

shows all your ips

查看更多
登录 后发表回答