Skip to content

fix: support non-standard X-Forwarded-For header formats#4605

Open
xingzihai wants to merge 2 commits intogin-gonic:masterfrom
xingzihai:fix-clientip-xforwardedfor-4572
Open

fix: support non-standard X-Forwarded-For header formats#4605
xingzihai wants to merge 2 commits intogin-gonic:masterfrom
xingzihai:fix-clientip-xforwardedfor-4572

Conversation

@xingzihai
Copy link
Copy Markdown

Summary

The ClientIP method did not properly handle non-standard X-Forwarded-For header formats:

  • IPv6 with brackets: [240e:318:2f4a:de56::240]
  • IPv4 with port: 192.168.8.39:38792
  • IPv6 with brackets and port: [240e:318:2f4a:de56::240]:38792

Problem

net.ParseIP cannot parse these formats directly, causing ClientIP to fail or return incorrect results.

Solution

  • Use net.SplitHostPort to handle formats with ports
  • Manually remove brackets for [IPv6] format
  • Added helper functions: normalizeIPFromHeader and tryRemoveBracketsAndParse

Changes

  • Modified validateHeader method in gin.go (+42 lines)
  • Added 3 test functions in gin_test.go (+255 lines)

Testing

Added comprehensive tests for:

  • IPv6 with brackets
  • IPv4 with port
  • IPv6 with brackets and port

Fixes #4572

)

This fix addresses issue gin-gonic#4572 where ClientIP method fails to parse
X-Forwarded-For headers with non-standard formats:
- IPv6 addresses with square brackets: [240e:318:2f4a:de56::240]
- IPv4 addresses with port: 192.168.8.39:38792
- IPv6 addresses with square brackets and port: [240e:318:2f4a:de56::240]:38792

Changes:
- Modified validateHeader() to normalize IP strings before parsing
- Added normalizeIPFromHeader() helper function to handle various formats
- Added tryRemoveBracketsAndParse() helper function for bracket removal
- Added comprehensive test cases for all non-standard formats

The fix uses net.SplitHostPort to handle IP:port and [IPv6]:port formats,
and manual bracket removal for [IPv6] format (which SplitHostPort doesn't handle).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Non-standard X-Forwarded-For header content is not supported

1 participant