For wired connections, enter ipconfig getifaddr en1 into the Terminal and your local IP will appear. For Wi-Fi, enter ipconfig getifaddr en0 and your local IP will appear. You can also see your public IP address in the Terminal: just type curl ifconfig.me and your public IP will pop up.
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
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:]+'
Generally, it is never guaranteed that a system will only have one IP address, for example, you can have both an ethernet and wlan connections, and if you have an active VPN connection then you'll have yet another IP address.
On Linux, hostname -I
will list the current IP address(es). Relying on it always returning just one IP address will most likely not work as expected under some scenarios (i.e. a VPN link is up, multiple ethernet adapters, etc), so a more reliable way would be converting the result to an array and then loop over the elements:
ips=($(hostname -I))
for ip in "${ips[@]}"
do
echo $ip
done
Note: If
hostname -I
returns the IP both in IPv4 and IPv6 formats then you can use insteadhostname -I | cut -f1 -d' '
to only show the IPv4 IP.
On OSX, if you know the interface, you could use:
~$ ipconfig getifaddr en0
# OUTPUT: 192.168.1.123
which will return just the IP address.
To detect dynamically the (first) active network interface on MacOS:
network_device=$(scutil --dns |awk -F'[()]' '$1~/if_index/ {print $2;exit;}')
ip=$(ipconfig getifaddr "$network_device")
echo $ip
### OUTPUT: 192.168.1.123
Also, getting the IP address becomes non-deterministic in case both a cable and wifi connections are established, when a machine has more than one ethernet interfaces, or when VPN tunnels are up.
If you need the external IP, then you can query a text-mode service, for example curl https://ipecho.net/plain
would return a plain text external IP.
A faster alternative is to query a known DNS server, e.g.:
dig @ns1-1.akamaitech.net ANY whoami.akamai.net +short
hostname -I
This command will give you the exact ip address as you want in Ubuntu.
On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.
hostname -I | awk '{print $1}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With