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\\.)|(
//RegEx to check for the following ranges. IPv4 only
//172.16-31.xxx.xxx
//10.xxx.xxx.xxx
//169.254.xxx.xxx
//192.168.xxx.xxx
var regex = /(^127\.)|(^(0)?10\.)|(^172\.(0)?1[6-9]\.)|(^172\.(0)?2[0-9]\.)|(^172\.(0)?3[0-1]\.)|(^169\.254\.)|(^192\.168\.)/;
I have generated this
REGEXP FOR CLASS A NETWORKS :
(10)(\.([2]([0-5][0-5]|[01234][6-9])|[1][0-9][0-9]|[1-9][0-9]|[0-9])){3}
REGEXP FOR CLASS B NETWORKS :
(172)\.(1[6-9]|2[0-9]|3[0-1])(\.(2[0-4][0-9]|25[0-5]|[1][0-9][0-9]|[1-9][0-9]|[0-9])){2}
REGEXP FOR CLASS C NETWORKS :
(192)\.(168)(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])){2}
Let me know if you encounter any error
If you are sure of your output (say for example netstat) and you have no need to check about IP address validity because it is already done, then you can catch private ip addresses with this formula
grep -P "(10.|192.168|172.1[6-9].|172.2[0-9].|172.3[01].).* "
FWIW this pattern was over 10% faster using pattern.matcher
:
^1((0)|(92\\.168)|(72\\.((1[6-9])|(2[0-9])|(3[0-1])))|(27))\\.
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])/