maxmind / getting-started-with-mmdb

A quick guide to writing and reading from your own MMDB databases.
37 stars 11 forks source link

Inserting each IP in the range into mmdb #17

Closed zanpakuto closed 10 months ago

zanpakuto commented 10 months ago

Background

The blog post - https://blog.maxmind.com/2015/09/building-your-own-mmdb-database-for-fun-and-profit/ goes as below:

"As in our first example, we’re create a new Net::Works::Network object. However, in this case we are going to insert each individual IP in the range. The reason for this is that we don’t know if our IP ranges match the ranges in the GeoLite2 database"

Code snippet from the post: (The Mashup)

`for my $range ( keys %address_for_employee ) {

my $user_metadata = $address_for_employee{$range};

# Iterate over network and insert IPs individually
my $**network** = Net::Works::Network->new_from_string( string => $**range** );
my $**iterator** = $network->iterator;

while ( my $**address** = $iterator->() ) {
    my $ip = $address->as_ipv4_string;
    my $model = $reader->city( ip => $ip );

    if ( $model->city->name ) {
        $user_metadata->{city} = $model->city->name;
    }
    if ( $model->country->name ) {
        $user_metadata->{country} = $model->country->name;
    }
    if ( $model->location->time_zone ) {
        $user_metadata->{time_zone} = $model->location->time_zone;
    }
    **$tree->insert_network( $**network**, $user_metadata );**
}

}`

Issue : Neither $ip, nor $address was used to insert data into the tree, which goes against the statement - "we are going to insert each individual IP in the range". Rather $network has been used

Also, as per the documentation - https://metacpan.org/pod/MaxMind::DB::Writer::Tree the method used for inserting into the tree - insert_network takes CIDR as argument, but not individual IP as argument.

How to write individual IP into the tree?

oschwald commented 10 months ago

To insert an individual IP, you would insert the network containing just that IP address. For instance, if the IP was 1.1.1.1, you would insert 1.1.1.1/32. Similarly, for IPv6, you would insert the /128.

Also, I would recommend using our Go writer rather than the Perl writer. It is likely the Perl writer will be deprecated in the near future.