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.
17pub fn estimate_original(current_ttl: u8) -> u8 {
18    for &initial in &INITIAL_TTLS {
19        if current_ttl <= initial {
20            return initial;
21        }
22    }
23    // Should be unreachable for u8, but fallback to 255
24    255
25}
26
27/// Estimate the number of hops the packet has traveled.
28///
29/// Calculated as `original_ttl - current_ttl`.
30pub fn estimate_hops(current_ttl: u8) -> u8 {
31    let original = estimate_original(current_ttl);
32    original.saturating_sub(current_ttl)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_estimate_original() {
41        assert_eq!(estimate_original(1), 32);
42        assert_eq!(estimate_original(30), 32);
43        assert_eq!(estimate_original(32), 32);
44
45        assert_eq!(estimate_original(33), 64);
46        assert_eq!(estimate_original(60), 64);
47        assert_eq!(estimate_original(64), 64);
48
49        assert_eq!(estimate_original(65), 128);
50        assert_eq!(estimate_original(100), 128);
51        assert_eq!(estimate_original(128), 128);
52
53        assert_eq!(estimate_original(129), 255);
54        assert_eq!(estimate_original(200), 255);
55        assert_eq!(estimate_original(255), 255);
56    }
57
58    #[test]
59    fn test_estimate_hops() {
60        assert_eq!(estimate_hops(30), 2); // 32 - 30
61        assert_eq!(estimate_hops(63), 1); // 64 - 63
62        assert_eq!(estimate_hops(54), 10); // 64 - 54
63        assert_eq!(estimate_hops(128), 0); // 128 - 128
64    }
65}