Skip to main content

stackforge_core/layer/ipv4/
ttl.rs

1//! TTL (Time To Live) utilities.
2//!
3//! Provides functions to guess the original TTL and number of hops
4//! based on the current TTL value.
5
6/// Common initial TTL values used by various operating systems.
7/// 32:  Some ancient systems
8/// 64:  Linux, macOS, modern Windows
9/// 128: Older Windows
10/// 255: Network infrastructure (Cisco, etc.)
11const INITIAL_TTLS: [u8; 4] = [32, 64, 128, 255];
12
13/// Estimate the original TTL based on the current TTL.
14///
15/// This finds the smallest standard initial TTL that is greater than
16/// or equal to the current TTL.
17#[must_use]
18pub fn estimate_original(current_ttl: u8) -> u8 {
19    for &initial in &INITIAL_TTLS {
20        if current_ttl <= initial {
21            return initial;
22        }
23    }
24    // Should be unreachable for u8, but fallback to 255
25    255
26}
27
28/// Estimate the number of hops the packet has traveled.
29///
30/// Calculated as `original_ttl - current_ttl`.
31#[must_use]
32pub fn estimate_hops(current_ttl: u8) -> u8 {
33    let original = estimate_original(current_ttl);
34    original.saturating_sub(current_ttl)
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn test_estimate_original() {
43        assert_eq!(estimate_original(1), 32);
44        assert_eq!(estimate_original(30), 32);
45        assert_eq!(estimate_original(32), 32);
46
47        assert_eq!(estimate_original(33), 64);
48        assert_eq!(estimate_original(60), 64);
49        assert_eq!(estimate_original(64), 64);
50
51        assert_eq!(estimate_original(65), 128);
52        assert_eq!(estimate_original(100), 128);
53        assert_eq!(estimate_original(128), 128);
54
55        assert_eq!(estimate_original(129), 255);
56        assert_eq!(estimate_original(200), 255);
57        assert_eq!(estimate_original(255), 255);
58    }
59
60    #[test]
61    fn test_estimate_hops() {
62        assert_eq!(estimate_hops(30), 2); // 32 - 30
63        assert_eq!(estimate_hops(63), 1); // 64 - 63
64        assert_eq!(estimate_hops(54), 10); // 64 - 54
65        assert_eq!(estimate_hops(128), 0); // 128 - 128
66    }
67}