在 Linux 中查看本机服务器的外网 IP(公网 IP)可以通过以下几种方法:
1. 使用 curl
查询外部服务(推荐)
bash
curl ifconfig.me
或:
bash
curl icanhazip.com
或:
bash
curl ipinfo.io/ip
这些服务会返回你的公网 IP 地址。
2. 使用 wget
替代 curl
bash
wget -qO- ifconfig.me
或:
bash
wget -qO- icanhazip.com
3. 使用 dig
查询 DNS 记录(适用于动态 DNS 或特定场景)
bash
dig +short myip.opendns.com @resolver1.opendns.com
4. 使用 host
或 nslookup
bash
host myip.opendns.com resolver1.opendns.com
或:
bash
nslookup myip.opendns.com resolver1.opendns.com
5. 使用 ip
或 ifconfig
查看本地网络接口(仅显示内网 IP,不推荐用于外网 IP)
bash
ip a
或:
bash
ifconfig
(这些命令通常只显示内网 IP,如 192.168.x.x
或 10.x.x.x
,不适用于直接获取公网 IP。)
注意事项:
-
如果服务器位于 NAT 或防火墙后(如家用路由器、云服务器内网环境),上述方法返回的是网关或云服务商分配的公网 IP。
-
某些云服务器(如 AWS、阿里云)的公网 IP 可能需要通过控制台或元数据服务查询,例如:
bashcurl http://169.254.169.254/latest/meta-data/public-ipv4 # AWS EC2
选择最简单的方法(如 curl ifconfig.me
)即可快速获取外网 IP。