I am trying to write a bash
script to get all IP addresses on a server. The script should work on all major distros. Here is what I have:
ifconf
Use grep -v to ignore 127.0.0.1
ifconfig | grep 'inet addr:' | awk {'print $2'} | grep -v '127.0.0.1'
Use sed to edit out the 'addr:'
ifconfig | grep 'inet addr:' | awk {'print $2'} | grep -v '127.0.0.1' | sed -e 's/addr://'
This is merely a distillation of several prior answers and comments. Sample output is included.
To list IPs:
Using ip
:
(Restricted to IPv4 and global)
$ /sbin/ip -4 -o addr show scope global | awk '{gsub(/\/.*/,"",$4); print $4}'
192.168.82.134
138.225.11.92
138.225.11.2
Using ifconfig
:
(Excluding 127.0.0.1)
$ /sbin/ifconfig | awk -F "[: ]+" '/inet addr:/ { if ($4 != "127.0.0.1") print $4 }'
192.168.82.134
138.225.11.92
138.225.11.2
To map IPs to hostnames, see this answer.
I'm always surprised to see people using sed and awk instead of perl.
But first, using both grep and awk with an extra option, feel free to just:
ifconfig | grep 'inet addr:' | awk {'print $2'} | awk -F: {'print $2'} | grep -v '127.0.0.1'
replacing the awks with perl:
ifconfig | grep 'inet addr:' | perl -F\\s\|: -ane 'print "$F[2]\n"' | grep -v '127.0.0.1'
replacing the greps within the same perl script:
ifconfig | perl -F\\s\|: -ane 'next if !/^inet addr:/ or /127\.0\.0\.1/; print "$F[2]\n"'
and lastly just using the power of perl's regex:
ifconfig | perl -ne 'next if !/inet addr:(?<ip>[0-9.]+)/ or $+{ip} == "127.0.0.1"; print "$+{ip}\n"'
ifconfig
was obsoleted by ip
. It also has the flag -o
that write outputs easy to parse. Use ip -4
to show only IPV4 addresses. Note the simpler script, it already exclude the loopback address:
ip -o addr | awk '!/^[0-9]*: ?lo|link\/ether/ {print $2" "$4}'
Or if you don't want the networks:
ip -o addr | awk '!/^[0-9]*: ?lo|link\/ether/ {gsub("/", " "); print $2" "$4}'
It's a very tricky solution but it works:
ip a | awk ' !/[0-9]+\: lo/ && /^[0-9]\:/ || /inet / && !/127\.0\.0\.1/ {print $2}'
Output:
eth0:
192.168.0.1/24
Better yet:
ip a | awk ' !/[0-9]+\: lo/ && /^[0-9]\:/ || /inet / && !/127\.0\.0\.1/ {print $2}' | perl -i -pe "s/:\n/: /g;" -pe "s/\/[\d]+$//"
Output:
eth0: 192.168.0.1
I don't have a machine with several non loopback interfaces I can check it with, feel free to post your findings.
Simply using hostname you can get a list of all your IP addresses, using the -I
flag.
i.e.
$ hostname --all-ip-addresses || hostname -I
10.10.85.100 10.20.85.100 10.30.85.100
whereas
$ hostname --ip-address || hostname -i
::1%1 127.0.0.1
Centos7 (k3.10.0)