Blog / Linux/ How to Get the Public IP Address on a Linux Server

How to Get the Public IP Address on a Linux Server

Linux 服务器获取公网 IP 地址的多种方法详解

Introduction

When managing Linux servers, you often need to retrieve the public IP address. This guide details several reliable methods to do so.

Method 1: Using the ifconfig Command (Legacy)

The traditional ifconfig command displays network interface information. Note that it may not be installed by default on newer distributions; the ip command (Method 2) is preferred.

/sbin/ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:"

Command Breakdown:

  • /sbin/ifconfig -a: Lists all network interfaces.
  • grep inet: Filters for IPv4 address lines.
  • grep -v 127.0.0.1: Excludes the loopback address.
  • grep -v inet6: Excludes IPv6 addresses.
  • awk '{print $2}': Prints the second column (the IP).
  • tr -d "addr:": Removes the 'addr:' string.

Method 2: Using the ip Command (Recommended)

The ip command is the modern, powerful tool for network configuration.

ip addr show | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}' | cut -d'/' -f1

For a specific interface (e.g., eth0):

ip -4 addr show eth0 | grep inet | awk '{print $2}' | cut -d'/' -f1

Replace eth0 with your actual public interface name.

Method 3: Querying External Services (Most Accurate)

For servers behind NAT or load balancers, the above methods may only show a private IP. Querying an external service returns the true egress IP.

Using curl:

curl -s ifconfig.me
curl -s icanhazip.com
curl -s ipinfo.io/ip
curl -s api.ipify.org

Using wget:

wget -qO- ifconfig.me

Note: This requires outbound internet access.

Method 4: Using host or dig (DNS Query)

If your server has a domain name, you can query it to get the public IP.

host $(hostname -f) | grep "has address" | awk '{print $4}'
dig +short $(hostname -f)

Summary & Best Practices

  • For the locally configured public IP: Use ip addr show.
  • For the true egress public IP: Use an external service (e.g., curl ifconfig.me).
  • In automation scripts, consider network connectivity and command availability, and implement error handling.

Tip: The legacy ifconfig command may not be available on newer systems and doesn't account for complex networks like NAT. This guide provides updated, more reliable methods.

Post a Comment

Your email will not be published. Required fields are marked with *.