Which terminal command to get just IP address and nothing else?
Categories:
How to Extract Just the IP Address from the Terminal
Learn various terminal commands to efficiently retrieve only your system's IP address, filtering out extraneous information for scripting and quick lookups.
When working with the command line, especially in scripting or network troubleshooting, you often need to quickly grab just the IP address without any additional interface details or verbose output. This article explores several common Unix-like commands and techniques to achieve this, focusing on precision and brevity.
Using ip
Command (Modern Linux)
The ip
command is the modern standard for network configuration on Linux. While powerful, its raw output can be overwhelming. We'll use grep
and awk
to filter precisely what we need. This method is highly reliable for extracting both IPv4 and IPv6 addresses.
ip -4 addr show scope global | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -1
Extracts the first global IPv4 address found.
ip -6 addr show scope global | grep -oP '(?<=inet6\s)[0-9a-fA-F:]+' | head -1
Extracts the first global IPv6 address found.
head -1
command is crucial if your system has multiple active network interfaces, ensuring you only get one IP address. Adjust or remove it if you need all IPs.Using ifconfig
Command (Legacy/macOS/BSD)
The ifconfig
command is a traditional tool for network interface configuration, still prevalent on macOS, BSD-based systems, and some older Linux distributions. Similar to ip
, it requires filtering to get just the IP address. The exact grep
and awk
patterns might vary slightly between systems due to output formatting differences.
ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | head -1
Extracts a non-localhost IPv4 address using ifconfig
.
Workflow for extracting an IP address using command-line tools.
External Services for Public IP Address
If you need your public IP address (the one visible to the internet), you can query external web services. This is especially useful when your local IP is behind a NAT or router.
curl -s icanhazip.com
Retrieves public IP address using icanhazip.com
.
dig +short myip.opendns.com @resolver1.opendns.com
Retrieves public IP address using OpenDNS resolver.