Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2025-09-18 17:22:25 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-21 16:09:51 * @FilePath: \go-toolbox\pkg\netx\ip.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
Index ¶
- func GetClientIP(r *http.Request) string
- func GetConNetPublicIP(urls ...string) (string, error)
- func GetLocalInterfaceIPAndExternalIP(urls ...string) (privateIP string, publicIP string, err error)
- func GetLocalInterfaceIPs() ([]net.IP, error)
- func GetPrivateIP() (string, error)
- func JoinHostPort(host string, port int) string
- func NormalizeIP(addr string) string
- func NormalizeListenAddr(addr string) string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetClientIP ¶
GetClientIP 从 HTTP 请求中提取客户端 IP 支持 IPv4 和 IPv6(包括 X-Forwarded-For / X-Real-IP 中的裸 IPv6 地址)
func GetConNetPublicIP ¶
GetConNetPublicIP 联网获取本机公网 IP
func GetLocalInterfaceIPAndExternalIP ¶
func GetLocalInterfaceIPAndExternalIP(urls ...string) (privateIP string, publicIP string, err error)
GetLocalInterfaceIPAndExternalIP 返回本地网卡对应的外部和内部 IP 地址
func GetLocalInterfaceIPs ¶
GetLocalInterfaceIPs 查询本机网卡所有IP
func JoinHostPort ¶
JoinHostPort 将 host 和 port 拼接为网络地址字符串 自动处理 IPv6 地址的方括号包裹:
- JoinHostPort("127.0.0.1", 8080) → "127.0.0.1:8080"
- JoinHostPort("::1", 8080) → "[::1]:8080"
- JoinHostPort("", 8080) → ":8080"
func NormalizeIP ¶
NormalizeIP 规范化 IP 地址字符串 处理以下 IPv6 场景:
- 去除方括号:[::1] → ::1
- 带端口无方括号:::1:8080 → ::1(尝试识别末尾端口)
- 纯 IPv6 地址:2001:db8::1 → 2001:db8::1(不变)
- IPv4 地址:192.168.1.1 → 192.168.1.1(不变)
func NormalizeListenAddr ¶
NormalizeListenAddr 规范化 net.Listen 地址,确保 IPv6 地址被方括号包裹 net.Listen 要求 IPv6 地址格式为 [::1]:port,但配置可能传入裸 IPv6:port 此函数自动检测并补齐方括号:
- "::1:5081" → "[::1]:5081"
- "2001:db8::1:5081" → "[2001:db8::1]:5081"
- "[::1]:5081" → "[::1]:5081"(已规范,不变)
- "127.0.0.1:5081" → "127.0.0.1:5081"(IPv4,不变)
- ":5081" → ":5081"(仅端口,不变)
Types ¶
This section is empty.