Getting Started with IP2Location.io in Rust: IP Geolocation Made Simple

IP2Location.io in Rust

Modern applications often need to know where their users are coming from. Whether it’s personalizing content, detecting suspicious logins, analyzing traffic, or blocking unwanted access, IP geolocation data has become an essential building block in web and security applications.

Recently, IP2Location.io released a new Rust SDK designed to help Rust developers work with IP geolocation data more easily. The IP2Location.io Rust SDK enables developers to quickly integrate the IP2Location.io API into their projects. In this tutorial, we’ll demonstrate how to use it in an existing project to enrich raw IP addresses with meaningful geolocation details such as country, city, ISP, and more.

Prerequisites

Before we get started, make sure you have an IP2Location.io API key. You can sign up for a free API key or purchase a paid plan to unlock more features.

Create a Rust project

In this section, we’ll show you how to create a new project that reads an Nginx log file, extracts all IP addresses, and counts how often they appear.

  1. In your terminal, navigate to your working directory and run:
cargo new log-analyzer
  1. Navigate to the newly created project folder and open src/main.rs. Add the following content:
use regex::Regex;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{self, BufRead};

fn main() -> io::Result<()> {
    // Expect a log file path from command line args
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("Usage: {} <log_file>", args[0]);
        std::process::exit(1);
    }

    let log_path = &args[1];
    let file = File::open(&log_path)?;
    let reader = io::BufReader::new(file);

    // Regex to capture IPv4 addresses
    let ip_regex = Regex::new(r"\b(\d{1,3}\.){3}\d{1,3}\b").unwrap();

    // Count occurrences of each IP
    let mut ip_counts: HashMap<String, usize> = HashMap::new();

    for line in reader.lines() {
        if let Ok(line) = line {
            for cap in ip_regex.find_iter(&line) {
                let ip = cap.as_str().to_string();
                *ip_counts.entry(ip).or_insert(0) += 1;
            }
        }
    }

    // Print results
    println!("Found IPs:");
    for (ip, count) in &ip_counts {
        println!("{} - {} times", ip, count);
    }

    Ok(())
}
  1. Add the regex dependency by running:
cargo add regex

Integrate IP2Location.io Rust SDK

Now, let’s integrate the IP2Location.io Rust SDK into the project. This will transform the basic analyzer into a geolocation-enriched log reporting tool.

  1. Install the SDK:
cargo add ip2locationio
  1. Replace the code in src/main.rs with the following:
use regex::Regex;
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::{self, BufRead};
use ip2locationio::{Client};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Expect a log file path from command line args
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("Usage: {} <log_file>", args[0]);
        std::process::exit(1);
    }
    // Create a single client instance
    let client = Client::new(Some("YOUR_API_KEY".to_string()));

    let log_path = &args[1];
    let file = File::open(&log_path)?;
    let reader = io::BufReader::new(file);

    // Regex to capture IPv4 addresses
    let ip_regex = Regex::new(r"\b(\d{1,3}\.){3}\d{1,3}\b").unwrap();

    // Count occurrences of each IP
    let mut ip_counts: HashMap<String, usize> = HashMap::new();

    for line in reader.lines() {
        if let Ok(line) = line {
            for cap in ip_regex.find_iter(&line) {
                let ip = cap.as_str().to_string();
                *ip_counts.entry(ip).or_insert(0) += 1;
            }
        }
    }

    // Print results
    println!("Found IPs:");
    for (ip, count) in &ip_counts {
	let ip_info = client.ip_geolocation().lookup(ip, None).await;
	let country_name = ip_info.unwrap().country_name.unwrap_or("Unknown".to_string());
        println!("{} ({:#?}) - {} times", ip, country_name, count);

    }

    Ok(())
}
  1. Run the project, and you should see an output similar to this:

Conclusion

By the end of this tutorial, you’ll have learned how to extract IP addresses from a server log file and process them. You’ll also know how to integrate the IP2Location.io Rust SDK into any Rust project to enrich logs with geolocation data.

Was this article helpful?

Related Articles