1 Star 0 Fork 0

tomatomeatman/GolangRepository

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
IpUtil.go 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
laowei 提交于 2024-07-15 14:55 +08:00 . bricks2准备
package data
import (
"net"
"strings"
Log "github.com/cihub/seelog"
"github.com/gin-gonic/gin"
)
type IpUtil struct{}
// 获取访问IP
func (iu IpUtil) GetIP(ctx *gin.Context) string {
ip := ctx.Request.Header.Get("X-Real-IP")
if net.ParseIP(ip) != nil {
return ip
}
ip = ctx.Request.Header.Get("X-Forward-For")
for _, i := range strings.Split(ip, ",") {
if net.ParseIP(i) != nil {
return ip
}
}
ip, _, err := net.SplitHostPort(ctx.Request.RemoteAddr)
if err != nil {
Log.Error("获取访问IP地址发生异常:", err) //使用localhost会得到这个IP
return "0.0.0.0"
}
if net.ParseIP(ip) == nil {
return ip
}
if "0:0:0:0:0:0:0:1" == ip {
ip = "127.0.0.1"
} else if "::1" == ip {
ip = "127.0.0.1"
}
if "127.0.0.1" != ip {
return ip
}
result, err := IpUtil{}.GetOutBoundIP()
if err != nil {
return ip
}
return result
}
// 获取本机ip地址
func (iu IpUtil) GetOutBoundIP() (ip string, err error) {
conn, err := net.Dial("udp", "8.8.8.8:53")
if err != nil {
Log.Error("获取本地IP地址发生异常:", err)
return
}
localAddr := conn.LocalAddr().(*net.UDPAddr)
ip = strings.Split(localAddr.String(), ":")[0]
return
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tomatomeatman/golang-repository.git
git@gitee.com:tomatomeatman/golang-repository.git
tomatomeatman
golang-repository
GolangRepository
fed9db1a323d

搜索帮助