Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What RegEx will match all loopback addresses?

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.1
  • 127.0.01
  • 127.0000.0000.1
  • 127.0.0.254
  • 127.63.31.15
  • 127.255.255.254
  • 0::1
  • 0000::0001
  • 0000:0:0000::01
  • 0000: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?

like image 960
Tullo_x86 Avatar asked Dec 08 '11 04:12

Tullo_x86


People also ask

Are all 127 addresses loopback?

IPv4 reserves all addresses in the range 127.0. 0.0 up to 127.255. 255.255 for use in loopback testing, although 127.0. 0.1 is (by convention) the loopback address used in almost all cases.

What is the regex for IP address?

// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."

What is universal loopback address?

The IP address 127.0. 0.1 is called a loopback address. Packets sent to this address never reach the network but are looped through the network interface card only. This can be used for diagnostic purposes to verify that the internal path through the TCP/IP protocols is working.

How many loopback addresses are there?

IPv4 network standards reserve the entire address block 127.0. 0.0/8 (more than 16 million addresses) for loopback purposes. That means any packet sent to any of those addresses is looped back.


1 Answers

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:

^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$

This RegEx matches

The string "localhost"

  • localhost
  • LOCALHOST

These permutations of the IPv4 loopback address

  • 127.0.0.1
  • 127.0.0.001
  • 127.0.00.1
  • 127.00.0.1
  • 127.000.000.001
  • 127.0000.0000.1
  • 127.0.01
  • 127.1
  • 127.001
  • 127.0.0.254
  • 127.63.31.15
  • 127.255.255.254

These permutations of the IPv6 loopback address

  • 0:0:0:0:0:0:0:1
  • 0000:0000:0000:0000:0000:0000:0000:0001
  • ::1
  • 0::1
  • 0:0:0::1
  • 0000::0001
  • 0000:0:0000::0001
  • 0000:0:0000::1
  • 0::0:1

This RegEx does not match

A valid server name

  • servername
  • subdomain.domain.tld

These valid IPv4 addresses

  • 192.168.0.1
  • 10.1.1.123

These valid IPv6 addresses

  • 0001::1
  • dead:beef::1
  • ::dead:beef:1
like image 192
Tullo_x86 Avatar answered Oct 06 '22 14:10

Tullo_x86