|
| 1 | +use maxminddb::Reader; |
| 2 | +use std::net::IpAddr; |
| 3 | +use std::path::Path; |
| 4 | +use trust_dns_resolver::config::{NameServerConfig, Protocol, ResolverConfig, ResolverOpts}; |
| 5 | +use trust_dns_resolver::TokioAsyncResolver; |
| 6 | + |
| 7 | +const OPENDNS_SERVER: &str = "208.67.222.222:53"; |
| 8 | +const OPENDNS_MYIP_DOMAIN: &str = "myip.opendns.com."; |
| 9 | +const GEOIP_DB_PATH: &str = "GeoLite2-Country.mmdb"; |
| 10 | + |
| 11 | +#[tokio::main] |
| 12 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 13 | + if let Ok(ip) = get_self_ip().await { |
| 14 | + println!("Public IP: {}", ip); |
| 15 | + if let Err(e) = map_ip_to_geo(ip) { |
| 16 | + println!("Error mapping IP to geo: {}", e); |
| 17 | + } |
| 18 | + } else { |
| 19 | + println!("Failed to get your IP address"); |
| 20 | + } |
| 21 | + Ok(()) |
| 22 | +} |
| 23 | + |
| 24 | +async fn get_self_ip() -> Result<IpAddr, Box<dyn std::error::Error>> { |
| 25 | + let mut config = ResolverConfig::new(); |
| 26 | + config.add_name_server(NameServerConfig { |
| 27 | + socket_addr: OPENDNS_SERVER.parse()?, |
| 28 | + protocol: Protocol::Udp, |
| 29 | + tls_dns_name: None, |
| 30 | + trust_negative_responses: false, |
| 31 | + bind_addr: None, |
| 32 | + }); |
| 33 | + let resolver = TokioAsyncResolver::tokio(config, ResolverOpts::default()); |
| 34 | + let response = resolver.lookup_ip(OPENDNS_MYIP_DOMAIN).await?; |
| 35 | + response.iter().next().ok_or_else(|| "No IP found".into()) |
| 36 | +} |
| 37 | + |
| 38 | +fn map_ip_to_geo(ip: IpAddr) -> Result<(), Box<dyn std::error::Error>> { |
| 39 | + let db_path = Path::new(GEOIP_DB_PATH); |
| 40 | + if !db_path.exists() { |
| 41 | + return Err(format!("GeoIP database file not found: {}", GEOIP_DB_PATH).into()); |
| 42 | + } |
| 43 | + |
| 44 | + let reader = Reader::open_readfile(GEOIP_DB_PATH)?; |
| 45 | + let result: maxminddb::geoip2::City = reader.lookup(ip)?; |
| 46 | + |
| 47 | + println!("{:#?}", result); |
| 48 | + |
| 49 | + let iso = result.country.unwrap().iso_code; |
| 50 | + println!("{iso:?}"); |
| 51 | + Ok(()) |
| 52 | +} |
0 commit comments