Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private IP Address Identifier in Regular Expression

I'm wondering if this is the best way to match a string that starts with a private IP address (Perl-style Regex):

(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9])|(^172\.3[0-1]) 

Thanks much!

like image 611
caseyamcl Avatar asked May 11 '10 19:05

caseyamcl


People also ask

How do you identify a private IP address?

Windows. Search for cmd in the Windows search bar, then in the command line prompt, type ipconfig to view the private IP address. Mac. Select system preferences, then click on network to view the private IP address.

How do you represent an IP address in regex?

\d{1,3}\b will match any IP address just fine. But will also match 999.999. 999.999 as if it were a valid IP address. If your regex flavor supports Unicode, it may even match ١٢٣.

Which IP address is a private IP address?

Private addresses include IP addresses from the following subnets: Range from 10.0. 0.0 to 10.255. 255.255 — a 10.0.

Which regex pattern can be used to find IP address?

Approach: Regex (Regular Expression) In C++ will be used to check the IP address. Specifying a range of characters or literals is one of the simplest criteria used in a regex.


2 Answers

I'm assuming you want to match these ranges:

 127.  0.0.0 – 127.255.255.255     127.0.0.0 /8  10.  0.0.0 –  10.255.255.255      10.0.0.0 /8 172. 16.0.0 – 172. 31.255.255    172.16.0.0 /12 192.168.0.0 – 192.168.255.255   192.168.0.0 /16 

You are missing some dots that would cause it to accept for example 172.169.0.0 even though this should not be accepted. I've fixed it below. Remove the new lines, it's just for readability.

(^127\.)| (^10\.)| (^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)| (^192\.168\.) 

Also note that this assumes that the IP addresses have already been validated - it accepts things like 10.foobar.

like image 61
Mark Byers Avatar answered Sep 30 '22 20:09

Mark Byers


This is the same as the correct answer by Mark, but now including IPv6 private addresses.

/(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/ 
like image 41
Edward Avatar answered Sep 30 '22 19:09

Edward