Private IP Address Identifier in Regular Expression

后端 未结 10 1288
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  一整个雨季
    2020-12-01 09:34

    This is in case you decide to go with my comment, suggesting you don't use regexps. Untested (but probably works, or at least close), in Perl:

    @private = (
        {network => inet_aton('127.0.0.0'),   mask => inet_aton('255.0.0.0')   },
        {network => inet_aton('192.168.0.0'), mask => inet_aton('255.255.0.0') },
        # ...
    );
    
    $ip = inet_aton($ip_text);
    if (grep $ip & $_->{mask} == $_->{network}, @private) {
        # ip address is private
    } else {
        # ip address is not private
    }
    

    Note now how @private is just data, which you can easily change. Or download on the fly from the Cymru Bogon Reference.

    edit: It occurs to me that asking for a Perl regexp doesn't mean you know Perl, so the key line is there is the 'grep', which just loops over each private address range. You take your IP, bitwise and it with the netmask, and compare to the network address. If equal, its part of that private network.

提交回复
热议问题