#!/bin/bash # 网络环境检测脚本 # 功能:检测公网 IPv4 和 IPv6 地址 # 作者:AI 助手 # 设置严格模式 set -euo pipefail # 日志函数 log() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" } # 错误处理函数 error() { log "❌ $*" >&2 exit 1 } # 警告处理函数 warn() { log "⚠️ $*" >&2 } # 信息输出函数 info() { log "📝 $*" } # 检查命令是否存在 has_cmd() { command -v "$1" &>/dev/null } # 获取公网 IPv4 地址 get_public_ipv4() { local timeout=10 local url="http://ipv4.icanhazip.com" if ! has_cmd curl; then error "curl 命令未找到,请安装 curl" fi local response response=$(curl -s -m "$timeout" "$url" 2>/dev/null) || { warn "无法连接到 IPv4 服务,请检查网络设置。" return 1 } # 检查返回的是否为有效的 IPv4 地址 if [[ $response =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then echo "$response" return 0 else warn "请求的服务返回异常数据:$response" return 1 fi } # 获取公网 IPv6 地址 get_public_ipv6() { local timeout=10 local url="http://ipv6.icanhazip.com" if ! has_cmd curl; then error "curl 命令未找到,请安装 curl" fi local response response=$(curl -s -m "$timeout" "$url" 2>/dev/null) || { warn "无法连接到 IPv6 服务,请检查网络设置。" return 1 } # 检查返回的是否为有效的 IPv6 地址(简化验证) if [[ $response =~ ^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$ ]]; then echo "$response" return 0 else warn "请求的服务返回异常数据:$response" return 1 fi } # 验证 IPv4 地址格式 is_valid_ipv4() { local ip="$1" if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then local IFS='.' local -a octets=($ip) for octet in "${octets[@]}"; do if [[ $octet -gt 255 ]]; then return 1 fi done return 0 fi return 1 } # 验证 IPv6 地址格式(简化验证) is_valid_ipv6() { local ip="$1" # 检查是否为有效的 IPv6 地址格式 if [[ $ip =~ ^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$ ]] || [[ $ip =~ ^::1$ ]] || [[ $ip =~ ^::$ ]]; then return 0 fi return 1 } # 主函数 main() { info "开始检测网络环境..." # 检测公网 IPv4 地址 info "检测公网 IPv4 地址..." local ipv4_result if ipv4_result=$(get_public_ipv4); then if is_valid_ipv4 "$ipv4_result"; then info "当前拥有公网 IPv4 地址:$ipv4_result" else warn "获取到的 IPv4 地址无效:$ipv4_result" fi else info "当前没有公网 IPv4 地址" fi # 检测公网 IPv6 地址 info "检测公网 IPv6 地址..." local ipv6_result if ipv6_result=$(get_public_ipv6); then if is_valid_ipv6 "$ipv6_result"; then info "当前拥有公网 IPv6 地址:$ipv6_result" else warn "获取到的 IPv6 地址无效:$ipv6_result" fi else info "当前没有公网 IPv6 地址" fi info "网络环境检测完成。" } # 执行主函数 if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main "$@" fi