@@ -453,18 +453,42 @@ fn ip_to_bytes(address: IpAddr) -> Vec<u8> {
453453}
454454
455455fn bytes_and_prefix_to_net ( bytes : & Vec < u8 > , prefix : u8 ) -> Result < IpNetwork , MaxMindDBError > {
456- let ip = match bytes. len ( ) {
457- 4 => IpAddr :: V4 ( Ipv4Addr :: new ( bytes[ 0 ] , bytes[ 1 ] , bytes[ 2 ] , bytes[ 3 ] ) ) ,
456+ let ( ip, pre) = match bytes. len ( ) {
457+ 4 => (
458+ IpAddr :: V4 ( Ipv4Addr :: new ( bytes[ 0 ] , bytes[ 1 ] , bytes[ 2 ] , bytes[ 3 ] ) ) ,
459+ prefix,
460+ ) ,
458461 16 => {
459- let a = ( bytes[ 0 ] as u16 ) << 8 | bytes[ 1 ] as u16 ;
460- let b = ( bytes[ 2 ] as u16 ) << 8 | bytes[ 3 ] as u16 ;
461- let c = ( bytes[ 4 ] as u16 ) << 8 | bytes[ 5 ] as u16 ;
462- let d = ( bytes[ 6 ] as u16 ) << 8 | bytes[ 7 ] as u16 ;
463- let e = ( bytes[ 8 ] as u16 ) << 8 | bytes[ 9 ] as u16 ;
464- let f = ( bytes[ 10 ] as u16 ) << 8 | bytes[ 11 ] as u16 ;
465- let g = ( bytes[ 12 ] as u16 ) << 8 | bytes[ 13 ] as u16 ;
466- let h = ( bytes[ 14 ] as u16 ) << 8 | bytes[ 15 ] as u16 ;
467- IpAddr :: V6 ( Ipv6Addr :: new ( a, b, c, d, e, f, g, h) )
462+ if bytes[ 0 ] == 0
463+ && bytes[ 1 ] == 0
464+ && bytes[ 2 ] == 0
465+ && bytes[ 3 ] == 0
466+ && bytes[ 4 ] == 0
467+ && bytes[ 5 ] == 0
468+ && bytes[ 6 ] == 0
469+ && bytes[ 7 ] == 0
470+ && bytes[ 8 ] == 0
471+ && bytes[ 9 ] == 0
472+ && bytes[ 10 ] == 0
473+ && bytes[ 11 ] == 0
474+ {
475+ // It's actually v4, but in v6 form, convert would be nice if ipnetwork had this
476+ // logic.
477+ (
478+ IpAddr :: V4 ( Ipv4Addr :: new ( bytes[ 12 ] , bytes[ 13 ] , bytes[ 14 ] , bytes[ 15 ] ) ) ,
479+ prefix - 96 ,
480+ )
481+ } else {
482+ let a = ( bytes[ 0 ] as u16 ) << 8 | bytes[ 1 ] as u16 ;
483+ let b = ( bytes[ 2 ] as u16 ) << 8 | bytes[ 3 ] as u16 ;
484+ let c = ( bytes[ 4 ] as u16 ) << 8 | bytes[ 5 ] as u16 ;
485+ let d = ( bytes[ 6 ] as u16 ) << 8 | bytes[ 7 ] as u16 ;
486+ let e = ( bytes[ 8 ] as u16 ) << 8 | bytes[ 9 ] as u16 ;
487+ let f = ( bytes[ 10 ] as u16 ) << 8 | bytes[ 11 ] as u16 ;
488+ let g = ( bytes[ 12 ] as u16 ) << 8 | bytes[ 13 ] as u16 ;
489+ let h = ( bytes[ 14 ] as u16 ) << 8 | bytes[ 15 ] as u16 ;
490+ ( IpAddr :: V6 ( Ipv6Addr :: new ( a, b, c, d, e, f, g, h) ) , prefix)
491+ }
468492 }
469493 // This should never happen
470494 _ => {
@@ -473,7 +497,7 @@ fn bytes_and_prefix_to_net(bytes: &Vec<u8>, prefix: u8) -> Result<IpNetwork, Max
473497 ) )
474498 }
475499 } ;
476- IpNetwork :: new ( ip, prefix ) . map_err ( |e| MaxMindDBError :: InvalidNetworkError ( e. to_string ( ) ) )
500+ IpNetwork :: new ( ip, pre ) . map_err ( |e| MaxMindDBError :: InvalidNetworkError ( e. to_string ( ) ) )
477501}
478502
479503fn find_metadata_start ( buf : & [ u8 ] ) -> Result < usize , MaxMindDBError > {
0 commit comments