#[cfg(feature = "web-monitoring")]
pub fn get_local_ip() -> Option<String> {
local_ip_address::local_ip().ok().map(|ip| ip.to_string())
}
#[cfg(not(feature = "web-monitoring"))]
pub fn get_local_ip() -> Option<String> {
None
}
pub fn build_access_url(bind_addr: &str, actual_port: u16) -> String {
let host = match bind_addr {
"0.0.0.0" => get_local_ip().unwrap_or_else(|| {
tracing::warn!("Could not determine local IP, using localhost (limited accessibility)");
"localhost".to_string()
}),
"127.0.0.1" | "localhost" => "localhost".to_string(),
addr => addr.to_string(),
};
format!("http://{}:{}", host, actual_port)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_build_access_url_localhost() {
let url = build_access_url("127.0.0.1", 8080);
assert_eq!(url, "http://localhost:8080");
let url = build_access_url("localhost", 3000);
assert_eq!(url, "http://localhost:3000");
}
#[test]
fn test_build_access_url_specific_address() {
let url = build_access_url("192.168.1.50", 9000);
assert_eq!(url, "http://192.168.1.50:9000");
}
#[test]
fn test_build_access_url_zero_address() {
let url = build_access_url("0.0.0.0", 8080);
assert!(url.starts_with("http://"));
assert!(url.ends_with(":8080"));
assert!(!url.contains("0.0.0.0"));
}
#[test]
#[cfg(feature = "web-monitoring")]
fn test_get_local_ip_returns_valid_ip() {
if let Some(ip) = get_local_ip() {
assert!(!ip.is_empty());
assert_ne!(ip, "127.0.0.1");
}
}
#[test]
#[cfg(not(feature = "web-monitoring"))]
fn test_get_local_ip_without_feature() {
assert!(get_local_ip().is_none());
}
}