Private IP Address Identifier in Regular Expression

后端 未结 10 1293
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 09:14

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\\.)|(         


        
10条回答
  •  旧时难觅i
    2020-12-01 09:34

    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"
    

提交回复
热议问题