美文网首页golangGolang 入门资料+笔记
go+gin获取本机ip和获取访问ip

go+gin获取本机ip和获取访问ip

作者: 五岁小孩 | 来源:发表于2021-01-21 17:40 被阅读0次

    <center><font size="5">go+gin 获取本机ip和获取访问ip</font></center>

    • 获取本机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
      }
      

    相关文章

      网友评论

        本文标题:go+gin获取本机ip和获取访问ip

        本文链接:https://www.haomeiwen.com/subject/qhvonktx.html