在 Linux 系统中,查询公网 IP 地址与查询内网 IP 地址有本质区别。由于多数服务器或主机处于NAT(网络地址转换)或防火墙之后,通过 ip addr 或 hostname -I 获取的通常只是局域网私有地址(如 192.168.x.x)。要获取真正的公网出口 IP,必须借助外部服务或公共 DNS 解析。

方法一:使用 curl 或 wget 访问外部 API(最常用且最准确)
这是最直接且通用的方法。Linux 系统通常预装了 curl 或 wget 工具。执行以下任意命令即可获取公网 IP:
curl ifconfig.me
curl ip.sb
curl icanhazip.com
curl ipinfo.io/ip
若系统仅安装了 wget,可使用:
wget -qO- ifconfig.me
方法二:利用 DNS 解析(无需 HTTP 请求,受防火墙限制更小)
此方法通过向公共 DNS 服务器发起查询,获取公网出口 IP。需要安装 dnsutils 或 bind-utils 包(包含 dig 命令)。
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
若使用 host 命令:
host myip.opendns.com resolver1.opendns.com
方法三:使用综合信息接口(中文友好,返回详细信息)
部分接口会返回详细的地理位置、ISP(互联网服务提供商)等信息。例如:
curl cip.cc
curl ipinfo.io
注意事项:内网 IP 与公网 IP 的区别
使用 ip addr 或 hostname -I 查询到的地址通常是内网 IP(如 10.0.0.0/8、172.16.0.0/12、192.168.0.0/16 等私有地址段)。只有通过上述外部访问方式(方法一、二、三)获取的才是真正的公网 IP。在容器或虚拟机中,若未配置桥接网络,公网 IP 查询结果通常为宿主机出口 IP。
总结:若需在脚本中自动获取公网 IP,推荐优先使用 curl ifconfig.me 或 dig +short myip.opendns.com @resolver1.opendns.com。前者兼容性最好,后者不依赖 HTTP 协议,在特定网络环境下更为可靠。

查看详情

查看详情