Regular Expressions 101

Community Patterns

HTTP Header - Hardcoded Routable IPv4 address with optional port

0

Regular Expression
PCRE (PHP <7.3)

/
Host: (?:(?:(?:22[0-3]|2[01]\d|1[79][013-9]|16[0-8]|12[0-68-9]|1[013-58]\d|[2-9]\d|1?[1-9])\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d))|(?:172\.(?:25[0-5]|2[0-4]\d|1\d{2}|[4-9]\d|3[2-9]|1[0-5]|\d))|(?:192\.(?:25[0-5]|2[0-4]\d|16[0-79]|1[0-57-9][0-9]|[1-9]\d|[0-9]))|(?:169\.(?:25[0-35]|2[0-4]\d|1\d{2}|[1-9]?\d)))(?:\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)){2}(?::(?:6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}))?[\r\n]
/
gm

Description

Matches valid internet-routable IPv4 addresses (Not RFC1918, RFC5735, RFC3927) with optional port delimited by colon.

I wrote this specifically for Snort rules that look for hardcoded IPv4 addresses in the HTTP Host header field, but I imagine this may have its uses aside from that.

This would have been much simpler to write using negative lookahead (NLA), but for kicks I did it without it. I know that NLA is not always supported, so this should work. If non-capture groups aren't supported either, you can just change (?: ) to ( ) and it should still work fine (*cough*Yara*cough*).

Just to be clear: This expression purposefully will not match:

  • Addresses that start with 0 (0.X.X.X)
  • Loopback addresses (127.0.0.0/8)
  • Addresses that start with 224 through 255 (Class D and E addresses)
  • Private IPs (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
  • APIPA (169.254.0.0/16)

The port expression will match ports from 1-65535.

Submitted by Damian Torres - 7 years ago