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条回答
Explosion°爆炸
2楼-- · 2019-01-29 20:09

You can write a script that only return the IP like:

/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'

For MAC:

ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\  -f2

Or for linux system

hostname -i | awk '{print $3}' # Ubuntu 

hostname -i # Debian
查看更多
We Are One
3楼-- · 2019-01-29 20:09

I always wind up needing this at the most unexpected times and, without fail, wind up searching for threads like this on SO. So I wrote a simple script to get IPv4 addresses via netstat, called echoip - you can find it here. The bash for network addresses looks like this, it also gets your public address from ipecho.net:

IPV4='\d+(\.\d+){3}'
INTERFACES=`netstat -i | grep -E "$IPV4" | cut -d ' ' -f 1`
INTERFACE_IPS=`netstat -i | grep -oE "$IPV4"`

for i in "${!INTERFACES[@]}"; do
  printf "%s:\t%s\n" "${INTERFACES[$i]}" "${INTERFACE_IPS[$i]}"
done

The echoip script yields an output like this:

$ echoip
public: 26.106.59.169
en0:    10.1.10.2
查看更多
萌系小妹纸
4楼-- · 2019-01-29 20:12

On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.

hostname -I | awk '{print $1}'
查看更多
闹够了就滚
5楼-- · 2019-01-29 20:12

I would Use Hostname -L to get just the IP to use as a variable in a script.

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

We can simply use only 2 commands ( ifconfig + awk ) to get just the IP (v4) we want like so:

On Linux, assuming to get IP address from eth0 interface, run the following command:

/sbin/ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'

On OSX, assumming to get IP affffdress from en0 interface, run the following command:

/sbin/ifconfig en0 | awk '/inet /{print $2}'
查看更多
看我几分像从前
7楼-- · 2019-01-29 20:14

In man hostname there is even more easier way which automatically excluding loopback IP and showing only space separated list of all assigned to host ip addresses:

root@srv:~# hostname --all-ip-addresses
11.12.13.14 192.168.15.19 

root@srv:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
   link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
   inet 127.0.0.1/8 scope host lo
   inet6 ::1/128 scope host 
   valid_lft forever preferred_lft forever
2: venet0: <BROADCAST,POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN 
  link/void 
  inet 11.12.13.14/32 scope global venet0:0
  inet 192.168.15.19/32 scope global venet0:1
查看更多
登录 后发表回答