获取本机IP
func GetLocalIP() []string {var ipStr []stringnetInterfaces, 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())}*///获取IPv4if 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 - 简书