golang 获取客户端IP

import (
	"github.com/thinkeridea/go-extend/exnet"
	"net"
	"net/http"
)

// RemoteIp 返回远程客户端的 IP,如 192.168.1.1
func RemoteIp(req *http.Request) string { 
	remoteAddr := req.RemoteAddr
	if ip := exnet.ClientPublicIP(req); ip != "" { 
		remoteAddr = ip
	} else if ip := exnet.ClientIP(req); ip != "" { 
		remoteAddr = ip
	} else if ip := req.Header.Get("X-Real-IP"); ip != "" { 
		remoteAddr = ip
	} else if ip = req.Header.Get("X-Forwarded-For"); ip != "" { 
		remoteAddr = ip
	} else { 
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}

	if remoteAddr == "::1" { 
		remoteAddr = "127.0.0.1"
	}

	return remoteAddr
}
    原文作者:成长中de大神
    原文地址: https://blog.csdn.net/qq_38083665/article/details/108537705
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞