在 Linux 系统中查看本机外网 IP 有多种方法,以下是几种常用的方式:
curl
查询公网 IP 服务(需联网,最常用方法)
curl ifconfig.me
或使用其他公共服务:
curl icanhazip.com
curl ipinfo.io/ip
curl api.ipify.org
说明:
- 这些公共服务会返回你的公网 IP(部分服务可能在国内访问不稳定)。
- 如果命令报错,可能需先安装 curl
(安装命令:sudo apt install curl
或 sudo yum install curl
)。
dig
查询 DNS 记录(适用于动态 DNS 场景)
dig +short myip.opendns.com @resolver1.opendns.com
说明:
- 需要安装 dnsutils
或 bind-utils
包(部分系统默认未安装)。
wget
替代 curl
wget -qO- ifconfig.me
如果主机位于内网,外网 IP 实际是路由器的 IP,可通过以下方式查看:
# 查看网关 IP(通常是路由器内网 IP)
ip route | grep default
# 登录路由器管理界面查询 WAN IP
ip
或 ifconfig
查看内网 IP(仅显示内网 IP,非公网 IP)
ip addr
# 或
ifconfig
注意:这些命令只会显示本地网卡配置的 IP(如 192.168.x.x
或 10.x.x.x
),不是外网 IP。
ip.sb
、ident.me
)。#!/bin/bash
echo "Public IP: $(curl -s ifconfig.me)"
选择最适合你的方法即可!