Regular Expression for X-Forwarded-For Values

588 Views Asked by At

I'm working on a regular expression that needs to validate the values of an incoming requests' x-forwarded-for header. The regex needs to validate both ipV4 and ipV6 address. Below are possible values that need to be validated.

192.168.1.1
192.168.1.1,192.168.1.2
192.168.1.1,2001:0db8:85a3:0000:0000:8a2e:0370:7334
2001:0db8:85a3:0000:0000:8a2e:0370:7334,2001:0db8:85a3:0000:0000:8a2e:0370:7335
2001:0db8:85a3:0000:0000:8a2e:0370:7334,192.168.1.1

The regular expression I'm using is

(((((?:((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4},? ?))+$)|([a-f0-9:]+:+)+[a-f0-9]+,? ?){0,4}|((((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4},? ?)){0,14})

The regular expression does not match when an ipV4 address is followed by an ipV6 address.

What needs to be changed to fix that error? Also, the regex as is pretty ugly (and expensive to run). Are there any optimizations that can be done?

1

There are 1 best solutions below

0
Gerg On

I figured out the regular expression.

(((((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4})|(([a-f0-9:]+:+)+[a-f0-9]+)),? ?){0,5}

This covers all the use cases I needed. For reference, I used this tool to test for Java. https://www.regexplanet.com/share/index.html?share=yyyypjwz90r