1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
//! asnames-rs is a library for simple Autonomous System (AS) names and country lookup
//!
//! # Data source
//!
//! - <https://ftp.ripe.net/ripe/asnames/asn.txt>
//!
//! # Data structure
//!
//! ```rust
//! #[derive(Debug, Clone)]
//! pub struct AsName {
//! pub asn: u32,
//! pub name: String,
//! pub country: String,
//! }
//! ```
//!
//! # Example
//!
//! ```rust
//! use std::collections::HashMap;
//! use asnames::{AsName, load_asnames};
//!
//! let asnames: HashMap<u32, AsName> = load_asnames().unwrap();
//! assert_eq!(asnames.get(&3333).unwrap().name, "RIPE-NCC-AS Reseaux IP Europeens Network Coordination Centre (RIPE NCC)");
//! assert_eq!(asnames.get(&400644).unwrap().name, "BGPKIT-LLC");
//! assert_eq!(asnames.get(&400644).unwrap().country, "US");
//! ```
use anyhow::Result;
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct AsName {
pub asn: u32,
pub name: String,
pub country: String,
}
const DATA_URL: &str = "https://ftp.ripe.net/ripe/asnames/asn.txt";
pub fn load_asnames() -> Result<HashMap<u32, AsName>> {
let lines = oneio::read_lines(DATA_URL)?;
let asnames = lines
.into_iter()
.filter_map(|line| {
let text = line.ok().unwrap();
let (asn_str, name_country_str) = match text.split_once(" ") {
Some((asn, name)) => (asn, name),
None => return None,
};
let (name_str, country_str) = match name_country_str.rsplit_once(", ") {
Some((name, country)) => (name, country),
None => return None,
};
Some(AsName {
asn: asn_str.parse::<u32>().unwrap(),
name: name_str.to_string(),
country: country_str.to_string(),
})
})
.collect::<Vec<AsName>>();
let mut asnames_map = HashMap::new();
for asname in asnames {
asnames_map.insert(asname.asn, asname);
}
Ok(asnames_map)
}