20 lines
696 B
Rust
20 lines
696 B
Rust
|
|
//! Socket-level options for TCP streams (keepalive, etc.).
|
||
|
|
//!
|
||
|
|
//! Uses `socket2::SockRef::from()` to borrow the raw fd without ownership transfer.
|
||
|
|
|
||
|
|
use std::io;
|
||
|
|
use std::time::Duration;
|
||
|
|
use tokio::net::TcpStream;
|
||
|
|
|
||
|
|
/// Apply TCP keepalive to a connected socket.
|
||
|
|
///
|
||
|
|
/// Enables SO_KEEPALIVE and sets the initial probe delay.
|
||
|
|
/// On Linux, also sets the interval between probes to the same value.
|
||
|
|
pub fn apply_keepalive(stream: &TcpStream, delay: Duration) -> io::Result<()> {
|
||
|
|
let sock_ref = socket2::SockRef::from(stream);
|
||
|
|
let ka = socket2::TcpKeepalive::new().with_time(delay);
|
||
|
|
#[cfg(target_os = "linux")]
|
||
|
|
let ka = ka.with_interval(delay);
|
||
|
|
sock_ref.set_tcp_keepalive(&ka)
|
||
|
|
}
|