获取本机IP
func GetLocalIP() []string {
var ipStr []string
netInterfaces, err := net.Interfaces()
if err != nil {
fmt.Println("net.Interfaces error:", err.Error())
return ipStr
}
for i := 0; i < len(netInterfaces); i++ {
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
addrs, _ := netInterfaces[i].Addrs()
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
//获取IPv6
/*if ipnet.IP.To16() != nil {
fmt.Println(ipnet.IP.String())
ipStr = append(ipStr, ipnet.IP.String())
}*/
//获取IPv4
if ipnet.IP.To4() != nil {
fmt.Println(ipnet.IP.String())
ipStr = append(ipStr, ipnet.IP.String())
}
}
}
}
}
return ipStr
}
获取访问IP
//获取ip
func GetRequestIP(c *gin.Context)string{
reqIP := c.ClientIP()
if reqIP == "::1" {
reqIP = "127.0.0.1"
}
return reqIP
}
参考来源:文章来源:https://www.toymoban.com/news/detail-810764.html
go+gin获取本机ip和获取访问ip - 简书文章来源地址https://www.toymoban.com/news/detail-810764.html
到了这里,关于Gin:获取本机IP,获取访问IP的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!