ip.go 528 B

123456789101112131415161718192021222324252627
  1. package common
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "strings"
  5. )
  6. func GetClientIP(c *gin.Context) string {
  7. ClientIP := c.ClientIP()
  8. //fmt.Println("ClientIP:", ClientIP)
  9. RemoteIP := c.RemoteIP()
  10. //fmt.Println("RemoteIP:", RemoteIP)
  11. ip := c.Request.Header.Get("X-Forwarded-For")
  12. if strings.Contains(ip, "127.0.0.1") || ip == "" {
  13. ip = c.Request.Header.Get("X-real-ip")
  14. }
  15. if ip == "" {
  16. ip = "127.0.0.1"
  17. }
  18. if RemoteIP != "127.0.0.1" {
  19. ip = RemoteIP
  20. }
  21. if ClientIP != "127.0.0.1" {
  22. ip = ClientIP
  23. }
  24. return ip
  25. }