curl 获取本机公网地址 (Ipv4 Ipv6)

如果你要用 curl 获取本机的 IPv6 地址,有两种常见场景:


一、获取本机公网 IPv6(通过外网服务查询)

你的机器必须能访问 IPv6 网络。

curl -6 https://ifconfig.co

其他可用服务:

curl -6 https://icanhazip.com
curl -6 https://ipv6.ip.sb
curl -6 https://api64.ipify.org

二、获取本机局域网 IPv6(不走外网)

curl 无法直接从系统接口获取 IPv6,需要使用 ip 命令:

只看本机的 IPv6 地址:

ip -6 addr show | grep "inet6"

更简洁:

ip -6 addr show scope global

只打印地址:

ip -6 addr show scope global | awk '{print $2}'

⚠️ 补充说明

  • curl 自身不能读取网卡信息,只能查询远程服务。
  • 如果你 curl 不出公网 IPv6,很可能机器默认路由没有 IPv6 或 DNS 解析没有 AAAA 记录。

如果你想知道「某个网卡(如 eth0)的 IPv6」,我也可以给你更精确命令。

如果你想用 curl 获取本机的公网 IPv4 地址,可以直接访问外部提供 IPv4 查询的服务。


✅ 最常用方式

强制使用 IPv4:

curl -4 https://ifconfig.co

其他可用服务:

curl -4 https://ipv4.ip.sb
curl -4 https://icanhazip.com
curl -4 https://api.ipify.org
curl -4 https://myip.ipip.net

🔍 如果需要纯 IPv4(不带多余文字)

curl -4 -s https://api.ipify.org

❗说明

  • curl 无法读取系统网卡,需要访问外部服务才能获取公网 IPv4。
  • 如果你的机器没有公网 IPv4(例如处于 NAT、只支持 IPv6),返回的值可能是代理出口的地址。

需要我给你一个可在脚本中使用的稳定 IPv4 查询命令吗?
给你一个 最稳定、最适合脚本使用 的 IPv4 查询方式(纯文本、无多余输出、支持超时、失败自动切换备份):


推荐脚本:稳健版获取本机公网 IPv4

#!/bin/bash

get_ipv4() {
  for url in \
    "https://api.ipify.org" \
    "https://ipv4.icanhazip.com" \
    "https://ipv4.ip.sb" \
    "https://ifconfig.co/ip"
  do
    ip=$(curl -4 -s --max-time 3 "$url")
    if [[ $? -eq 0 && -n "$ip" ]]; then
      echo "$ip"
      return 0
    fi
  done
  return 1
}

get_ipv4

🔥 特点

  • 强制 IPv4 (-4)
  • 超时 3 秒(避免脚本卡死)
  • 自动轮询多个地址服务
  • 只输出纯 IPv4 字符串(支持脚本解析)
  • 兼容 Debian / Ubuntu / Alpine / CentOS

🧪 最简单单行版本

如果你只需要一个极简命令:

curl -4 -s https://api.ipify.org

如果你想,我可以再给你一个 同时获取 IPv4 + IPv6 的脚本版本。

评论栏