In today’s interconnected world, tracking network information like IP addresses and hostnames is crucial for network management, security, and troubleshooting. This article introduces the IP File Logger project, a Rust-based program designed to log the current global IP address and hostname of a network into a CSV file. This project showcases Rust’s capabilities in network programming, file handling, and cross-platform development.
You can find the source code for this project in github link here.
Project Overview
The IP File Logger is a simple yet powerful Rust application that retrieves the current global IP address using the ipify API, fetches the local machine’s hostname, and logs this information into a CSV file. The program ensures that it only appends new entries when there is a change in the IP address or hostname, thus avoiding redundant records.
Key Features
- Global IP Address Logging: Utilizes the ipify API to fetch the current global IP address.
- Hostname Logging: Captures and logs the local machine’s hostname.
- Conditional Logging: Prevents redundant entries by checking if the latest log already contains the current IP address and hostname.
- Cross-Platform Support: Written in Rust, the program can be compiled to run on various platforms, including Windows, Linux, and macOS.
Setting Up the Project
To set up the IP File Logger project, follow these steps:
1. Install Rust: Ensure Rust is installed on your system. You can install it using rustup.
2. Create a New Rust Project:
cargo new ip_file_logger
cd ip_file_logger
3. Add Dependencies: In the Cargo.toml
file, add the necessary dependencies:
[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }
csv = "1.1"
chrono = "0.4"
4. Implement the Program: Replace the content of main.rs
with the following code:
use std::error::Error;
use std::fs::OpenOptions;
use std::io::{BufRead, BufReader};
use chrono::Utc;
use csv::Writer;
fn get_public_ip() -> Result<String, Box<dyn Error>> {
let response = reqwest::blocking::get("https://api.ipify.org")?;
Ok(response.text()?)
}
fn get_hostname() -> Result<String, Box<dyn Error>> {
let output = std::process::Command::new("hostname").output()?;
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
fn main() -> Result<(), Box<dyn Error>> {
// Get the CSV file path from the command-line arguments
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <path_to_csv>", args[0]);
return Ok(());
}
let csv_path = &args[1];
// Get the public IP address and hostname
let ip_address = get_public_ip()?;
let hostname = get_hostname()?;
let date = Utc::now().to_string();
// Open or create the CSV file and check the last record
let file = OpenOptions::new().read(true).write(true).create(true).open(csv_path)?;
let reader = BufReader::new(file.try_clone()?);
let mut writer = Writer::from_writer(file);
let mut last_hostname = String::new();
let mut last_ip = String::new();
for line in reader.lines() {
if let Ok(record) = line {
let fields: Vec<&str> = record.split(',').collect();
if fields.len() == 3 {
last_hostname = fields[1].to_string();
last_ip = fields[2].to_string();
}
}
}
if last_hostname != hostname || last_ip != ip_address {
writer.write_record(&[date, hostname, ip_address])?;
writer.flush()?;
}
Ok(())
}
Running the Program
To run the program and log network information to a CSV file:
cargo run --release /path/to/ip_log.csv
Replace /path/to/ip_log.csv
with the desired path for your CSV file.
Cross-Compiling for Windows
To compile the program for Windows on a Linux system, follow these steps:
1. Install the Windows Target:
rustup target add x86_64-pc-windows-gnu
2. Install MinGW-w64:
sudo apt update
sudo apt install mingw-w64
3. Build the Project:
cargo build --release --target x86_64-pc-windows-gnu
The IP File Logger project demonstrates how to use Rust for practical network-related tasks. By leveraging Rust’s powerful ecosystem and cross-platform capabilities, this project provides a robust solution for logging network information. Whether you’re managing a network or developing cross-platform applications, Rust proves to be a valuable tool in your development toolkit.