I have an application which must warn the user upon use of localhost, 127.0.0.1, ::1, or any loopback address (the target host is used for a database-to-database connection not necessarily inside of the environment of the application). This is made complicated because addresses like the following…
127.1127.0.01127.0000.0000.1127.0.0.254127.63.31.15127.255.255.2540::10000::00010000:0:0000::010000:0000:0000:0000:0000:0000:0000:0001
…will parse properly by the consuming code, and will resolve to loopback.
What is a regular expression which will match any permutation of the IPv4 and IPv6 loopback addresses?
After a short time fiddling around in RegexBuddy (which is a truly magnificent tool for test-driven RegEx construction), I have come up with this:
This RegEx matches
The string “localhost”
localhostLOCALHOSTThese permutations of the IPv4 loopback address
127.0.0.1127.0.0.001127.0.00.1127.00.0.1127.000.000.001127.0000.0000.1127.0.01127.1127.001127.0.0.254127.63.31.15127.255.255.254These permutations of the IPv6 loopback address
0:0:0:0:0:0:0:10000:0000:0000:0000:0000:0000:0000:0001::10::10:0:0::10000::00010000:0:0000::00010000:0:0000::10::0:1This RegEx does not match
A valid server name
servernamesubdomain.domain.tldThese valid IPv4 addresses
192.168.0.110.1.1.123These valid IPv6 addresses
0001::1dead:beef::1::dead:beef:1