🌏 閱讀中文版本
Introduction
In modern networking environments, knowing your external IP address is essential for network troubleshooting, remote access configuration, server setup, and many other scenarios. For Ubuntu users, the command line offers the fastest and most efficient way to query your public IP address.
This guide introduces multiple methods to find your external IP address using the Ubuntu command line, along with explanations of the advantages, disadvantages, and best use cases for each approach.
Why Do You Need to Know Your External IP?
Your external IP address (also known as public IP or WAN IP) is your unique identifier on the internet. Here are some common scenarios where you’ll need it:
- Remote Access Configuration: Setting up SSH, VPN, or remote desktop requires knowing the target host’s public IP
- Firewall Rules: Configuring IP whitelists or blacklists
- Network Troubleshooting: Verifying successful internet connectivity
- Server Monitoring: Tracking changes to your server’s public IP
- Geolocation Verification: Confirming the geographic region of your current network
Method 1: Using curl Command
1. Using ifconfig.me
This is the quickest and simplest method:
# Query external IPv4 address
curl ifconfig.me
# Query detailed information (IP, hostname, user agent)
curl ifconfig.me/all
# Get IP only (silent mode)
curl -s ifconfig.me
2. Using icanhazip.com
This service offers fast and reliable responses:
# IPv4 address
curl ipv4.icanhazip.com
# IPv6 address
curl ipv6.icanhazip.com
# Auto-detect (IPv4 or IPv6)
curl icanhazip.com
3. Using api.ipify.org
Provides API-formatted responses, ideal for script processing:
# Plain text format
curl https://api.ipify.org
# JSON format
curl https://api.ipify.org?format=json
# Example output: {"ip":"203.0.113.45"}
Method 2: Using wget Command
If curl is not installed on your system, you can use wget:
# Query IP with wget
wget -qO- ifconfig.me
# Using icanhazip.com
wget -qO- icanhazip.com
# Using ipinfo.io (JSON format)
wget -qO- ipinfo.io
Parameter explanation:
-q: Quiet mode (suppress download progress)-O-: Output to standard output instead of file
Method 3: Using dig Command
Retrieve IP address via DNS query (useful when HTTP services are unavailable):
# Using OpenDNS resolver
dig +short myip.opendns.com @resolver1.opendns.com
# Using Google DNS
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | tr -d '"'
# Using Akamai DNS
dig +short @ns1-1.akamaitech.net ANY whoami.akamai.net
Method 4: Using host Command
Simple DNS query method:
# Using OpenDNS
host myip.opendns.com resolver1.opendns.com | grep "myip.opendns.com has" | awk '{print $NF}'
Method 5: Using nc (netcat)
Retrieve IP via TCP connection to a specific service:
# Using icanhazip.com (port 80)
echo -e "GET / HTTP/1.1nHost: icanhazip.comn" | nc icanhazip.com 80 | tail -1
Method Comparison
| Method | Advantages | Disadvantages | Best Use Cases |
|---|---|---|---|
curl |
Simple, fast, widely used | Requires curl installation | General use, script automation |
wget |
Pre-installed on Ubuntu | More complex syntax | When curl is not available |
dig |
Uses DNS protocol, no HTTP dependency | Requires dnsutils package | When HTTP is blocked by firewall |
host |
Lightweight, simple | Output requires parsing | Basic queries |
nc |
Low-level control | Complex, requires manual parsing | Advanced debugging |
Practical Script Examples
Automatic IP Change Monitoring
#!/bin/bash
# Monitor external IP changes and log them
LOG_FILE="/var/log/external_ip.log"
CURRENT_IP=$(curl -s ifconfig.me)
LAST_IP=$(tail -1 "$LOG_FILE" 2>/dev/null | awk '{print $3}')
if [ "$CURRENT_IP" != "$LAST_IP" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') IP changed: $CURRENT_IP" >> "$LOG_FILE"
# Add notification mechanism here (email, Slack, etc.)
fi
Multi-Service Validation
#!/bin/bash
# Query multiple services and compare results
echo "Querying external IP address..."
IP1=$(curl -s ifconfig.me)
IP2=$(curl -s icanhazip.com)
IP3=$(curl -s https://api.ipify.org)
echo "ifconfig.me: $IP1"
echo "icanhazip.com: $IP2"
echo "ipify.org: $IP3"
# Check consistency
if [ "$IP1" == "$IP2" ] && [ "$IP2" == "$IP3" ]; then
echo "✓ All services returned the same IP: $IP1"
else
echo "⚠ Warning: Different services returned inconsistent results"
fi
Installing Required Tools
If your system is missing certain tools, install them with these commands:
# Install curl
sudo apt update
sudo apt install curl -y
# Install dnsutils (includes dig and host)
sudo apt install dnsutils -y
# Install netcat
sudo apt install netcat -y
Security Considerations
Privacy Risks
Your external IP address may reveal the following information:
- Geographic Location: Approximate country and city
- ISP Information: Internet service provider name
- Organization Information: Corporate or educational network
Recommendations:
- Do not share your external IP in public forums
- Consider using VPN or proxy servers for privacy protection
- Regularly check firewall rules to restrict unnecessary external access
Third-Party Service Risks
When using external services to query your IP, be aware that:
- Query logs may be retained by service providers
- Some services may be unstable or go offline
- Use well-known, trusted services
Frequently Asked Questions
Q1: Why does my IP address change?
Most home networks use dynamic IP (DHCP-assigned), and ISPs periodically rotate your IP address. Businesses and servers typically use static IP.
Q2: How do I get my IPv6 address?
Use IPv6-enabled services:
curl ipv6.icanhazip.com
curl -6 ifconfig.me
Q3: How do I display both internal and external IP?
# Internal IP (local network)
hostname -I
# External IP (public network)
curl ifconfig.me
# Combined display
echo "Internal IP: $(hostname -I)"
echo "External IP: $(curl -s ifconfig.me)"
Q4: Why does the curl command not respond?
Possible reasons:
- Network connection issue: Check with
ping 8.8.8.8 - Firewall blocking: Check iptables or ufw rules
- curl not installed: Run
sudo apt install curl - Service temporarily unavailable: Try other services
Q5: Can I automate this in scripts?
Yes. Use the following approach:
# Use in scripts (with error handling)
EXTERNAL_IP=$(curl -s --max-time 5 ifconfig.me)
if [ -z "$EXTERNAL_IP" ]; then
echo "Error: Unable to retrieve external IP"
exit 1
fi
echo "External IP: $EXTERNAL_IP"
Conclusion
This guide introduced 5 methods to find your external IP address on Ubuntu’s command line:
- curl command: Most common and simplest (recommended)
- wget command: Suitable for systems without curl
- dig command: Uses DNS queries, no HTTP dependency
- host command: Lightweight DNS query
- netcat: Low-level TCP connection query
Recommended usage:
- Daily use:
curl ifconfig.me - Script automation:
curl -s https://api.ipify.org - Firewall-restricted environments:
dig +short myip.opendns.com @resolver1.opendns.com
Whichever method you choose, remember to consider privacy and security—don’t casually share your external IP address.
Related Articles
- Deploy .NET Applications on Ubuntu: Complete Guide (English)
- Ubuntu Server Auto-Update Complete Guide: Enterprise Strategy, Risk Control & Failure Recovery
- How to Set Up CloudFront IP Whitelist with AWS WAF
- 如何使用 AWS WAF 設定 CloudFront IP 白名單
- Build RHEL / Rocky Linux Training Environment on Mac: Virtualization Options, Installation Process, and Training Focus