Private IP Address Identifier in Regular Expression
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])/
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
.
here is what I use in python:
rfc1918 = re.compile('^(10(\.(25[0-5]|2[0-4][0-9]|1[0-9]{1,2}|[0-9]{1,2})){3}|((172\.(1[6-9]|2[0-9]|3[01]))|192\.168)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{1,2}|[0-9]{1,2})){2})$')
You can remove the ^ and/or $ anchors if you wish.
I prefer the above regex because it weeds out invalid octets (anything above 255).
example usage:
if rfc1918.match(ip):
print "ip is private"
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].).* "