开发者

Regex for IPv4 Routable address only

What is a regex that can find a routable IPv4 addresses only? EG, does no开发者_StackOverflowt match 192.0.2.1/24, 127.0.0.1, etc. Google seems to only find the all too common 'is an ip address' regex.


Trying to implement business rules in a regex is a bad idea.

Just parse the IP address, and check whether it satisfies your criteria in code.


Try this one:

^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!172\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))(?<!127)(?<!^10)(?<!^0)\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!192\.168)(?<!172\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!\.0$)(?<!\.255$)$

It correctly doesn't match this invalid ips:

999.999.999.999.
108.0.0.01
0.1.2.3
00.0000.00.00
192.168.1.1
912.456.123.123
.3.3.3.0
3.2.2.0
192.168.0.0
18.16.0.0

It doesn't match local IPs:

172.16.0.9
172.16.4.1
172.17.1.1
127.0.0.2
10.0.1.5
10.0.0.1
10.155.155.155
10.255.255.254
172.16.0.4
172.16.0.1
172.17.1.1
172.31.254.254

Finally it doesn't match broadcast IPs:

60.123.247.255
196.168.255.255
10.255.255.255
192.168.255.255

Every other IP i've tested is a match so far, but I haven't done it thoroughly, so there might be some bugs.


You can't do this in a regex anyway, not efficiently. Parse it, then check against the special-case addresses (multicast, RFC 1918, etc).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜