在管理云服务器时,很多时候你已经通过 SSH 登录,但想确认服务器的 公网 IP(对外访问互联网的地址)或 内网 IP(私网 IP)时,需要怎么做?
最常用的方法是:
bashcurl -4 ifconfig.me
或者:
bashcurl ipinfo.io/ip
输出的就是服务器访问互联网时使用的公网 IP,简单直接。
云服务器通常有两种 IP:
新手登录 SSH 后,经常只能看到内网 IP,不确定公网 IP,因此需要命令或云厂商提供的方式查询。
bashcurl -4 ifconfig.me
或者:
bashcurl ipinfo.io/ip
输出公网 IP,即服务器对外访问互联网的地址。
bashdig +short myip.opendns.com @resolver1.opendns.com
或者:
bashhost myip.opendns.com resolver1.opendns.com
利用 DNS 服务快速获取公网 IP。
控制台查看 云厂商(阿里云、AWS、腾讯云等)通常在控制台直接显示分配的公网 IP。
查看本机网卡(可能只显示内网 IP)
baship addr show
注意:网卡上一般显示的是私网 IP(10.x / 172.x / 192.168.x),公网 IP 通常通过 NAT 映射。
为了方便,可以写一个脚本,直接显示 内网 IP(所有网卡,IPv4/IPv6)、公网 IP(IPv4/IPv6),并使用 DNS 验证公网 IP:
bash#!/bin/bash
# get_ip_full.sh - 升级版:显示内网、公网 IPv4/IPv6,并验证公网 IP
echo "=== 云服务器 IP 信息 ==="
# 1️⃣ 内网 IP
echo "内网 IP:"
ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '^127\.' || echo "未找到 IPv4"
ip -6 addr show | grep -oP '(?<=inet6\s)[\da-f:]+(?=/)' | grep -v '^::1' || echo "未找到 IPv6"
# 2️⃣ 公网 IP IPv4
echo -n "公网 IPv4: "
if command -v curl >/dev/null 2>&1; then
curl -4 -s ifconfig.me || echo "获取失败"
elif command -v wget >/dev/null 2>&1; then
wget -4 -qO- ifconfig.me || echo "获取失败"
else
echo "请安装 curl 或 wget"
fi
# 3️⃣ 公网 IP IPv6
echo -n "公网 IPv6: "
if command -v curl >/dev/null 2>&1; then
curl -6 -s ifconfig.me || echo "获取失败"
elif command -v wget >/dev/null 2>&1; then
wget -6 -qO- ifconfig.me || echo "获取失败"
else
echo "请安装 curl 或 wget"
fi
# 4️⃣ DNS 验证公网 IP(IPv4)
echo -n "DNS 验证公网 IP: "
dig +short myip.opendns.com @resolver1.opendns.com || echo "获取失败"
echo "========================"
bashchmod +x get_ip_full.sh
./get_ip_full.sh
示例输出:
=== 云服务器 IP 信息 === 内网 IP: 192.168.1.10 fe80::1a2b:3c4d:5e6f 公网 IPv4: 123.45.67.89 公网 IPv6: 2001:db8::1234 DNS 验证公网 IP: 123.45.67.89 ========================
curl ifconfig.me
或 curl ipinfo.io/ip
本质上是向外部回显服务发起 HTTP 请求。所以你看到的就是服务器对外的出口 IP。
-4
/ -6
参数-4
强制使用 IPv4-6
强制使用 IPv6服务 | 输出 | 特点 |
---|---|---|
ifconfig.me | 纯文本 IP | 简单、轻量、响应快,适合脚本 |
ipinfo.io | IP + JSON 元信息 | 包含城市、运营商、ASN 等,适合开发查询;有配额限制 |
https://
保护传输安全bashcurl -s https://ipinfo.io/json | jq .
bashdig +short myip.opendns.com @resolver1.opendns.com
curl -4 ifconfig.me
或 curl ipinfo.io/ip
get_ip_full.sh
一次性显示内网、公网 IPv4/IPv6 并验证本文作者:GYC
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!