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 loo
If you have limited environment, you may use this command:
ip -4 addr show dev eth0 | grep inet | tr -s " " | cut -d" " -f3 | head -n 1
Here is my version, in which you can pass a list of interfaces, ordered by priority:
getIpFromInterface()
{
interface=$1
ifconfig ${interface} > /dev/null 2>&1 && ifconfig ${interface} | awk -F'inet ' '{ print $2 }' | awk '{ print $1 }' | grep .
}
getCurrentIpAddress(){
IFLIST=(${@:-${IFLIST[@]}})
for currentInterface in ${IFLIST[@]}
do
IP=$(getIpFromInterface $currentInterface)
[[ -z "$IP" ]] && continue
echo ${IP/*:}
return
done
}
IFLIST=(tap0 en1 en0)
getCurrentIpAddress $@
So if I'm connected with VPN, Wifi and ethernet, my VPN address (on interface tap0) will be returned. The script works on both linux and osx, and can take arguments if you want to override IFLIST
Note that if you want to use IPV6, you'll have to replace 'inet ' by 'inet6'.
If you don't want to use ifconfig
nor regex...
ip addr | grep eth0 | grep inet | awk '{print $2}' | cut -d"/" -f1
To print only the IP address of eth0
, without other text:
ifconfig eth0 | grep -Po '(?<=inet addr:)[\d.]+'
To determine your primary interface (because it might not be "eth0"), use:
route | grep ^default | sed "s/.* //"
The above two lines can be combined into a single command like this:
ifconfig `route | grep ^default | sed "s/.* //"` \
| grep -Po '(?<=inet addr:)[\d.]+'
curl ifconfig.co
This returns only the ip address of your system.
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:]+'