maxmind / getting-started-with-mmdb

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

Looking up an IP doesn't get most specific result #13

Closed jonathan-kosgei closed 5 years ago

jonathan-kosgei commented 5 years ago

I'm writing 2 networks into an mmdb 8.0.0.0/12 and 8.8.8.0/24 with 2 different values. When I lookup the IP 8.8.8.8 from that mmdb it gives me the value associated with 8.0.0.0/12 and not 8.8.8.0/24.

Here is the script I used and the lookup in Python;

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw( say );

use MaxMind::DB::Writer::Tree;

my $filename = 'users.mmdb';

my %types = (
    asn             => 'utf8_string',
);

my $tree = MaxMind::DB::Writer::Tree->new(

    database_type => 'My-IP-Data',
    description =>
        { en => 'My database of IP data', fr => "Mon Data d'IP", },
    ip_version => 4,
    map_key_type_callback => sub { $types{ $_[0] } },
    record_size => 24,
);

my %asn_data = (
    '8.0.0.0/12' => {
        asn          => '3356',
    },
    '8.8.8.0/24' => {
        asn          => '15169',
    },
);

for my $network ( keys %asn_data ) {
    $tree->insert_network( $network, $asn_data{$network} );
}

# Write the database to disk.
open my $fh, '>:raw', $filename;
$tree->write_tree( $fh );
close $fh;

say "$filename has now been created";

Lookup

import maxminddb

asn_file = maxminddb.open_database('users.mmdb')
asn_file.get('8.8.8.8')

The expected behavior is to get the result associated with 8.8.8.0/24.

oschwald commented 5 years ago

The last insert wins. This means if you insert the /12 after the /24, the /24 would be overwritten. As written, your code will insert them in a random order. You should ensure that the /24 is inserted after the /12.