ip.go 528 B

12345678910111213141516171819202122232425262728
  1. package utils
  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. }