You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ipUtil.go 992 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package utils
  2. import (
  3. "net"
  4. "net/http"
  5. "strings"
  6. )
  7. func GetClientIP(r *http.Request) string {
  8. // 检查反向代理设置的常用头信息(按优先级排序)
  9. headers := []string{
  10. "X-Forwarded-For",
  11. "X-Real-Ip",
  12. "Proxy-Client-IP",
  13. "WL-Proxy-Client-IP",
  14. "HTTP_CLIENT_IP",
  15. "HTTP_X_FORWARDED_FOR",
  16. }
  17. for _, header := range headers {
  18. ip := r.Header.Get(header)
  19. if ip != "" {
  20. // 处理多IP情况(取第一个有效IP)
  21. parts := strings.Split(ip, ",")
  22. for _, part := range parts {
  23. ip = strings.TrimSpace(part)
  24. if ip != "" && !strings.EqualFold(ip, "unknown") {
  25. return parseIP(ip)
  26. }
  27. }
  28. }
  29. }
  30. // 回退到直接连接IP(带端口时需要处理)
  31. ip, _, err := net.SplitHostPort(r.RemoteAddr)
  32. if err != nil {
  33. return r.RemoteAddr // 无端口的情况直接返回
  34. }
  35. return parseIP(ip)
  36. }
  37. // 处理特殊格式IP(如IPv6本地地址)
  38. func parseIP(ip string) string {
  39. if ip == "::1" {
  40. return "127.0.0.1"
  41. }
  42. return ip
  43. }

PCM is positioned as Software stack over Cloud, aiming to build the standards and ecology of heterogeneous cloud collaboration for JCC in a non intrusive and autonomous peer-to-peer manner.