1use std::os::unix::io::AsRawFd;
2use std::io;
3
4use queen_io::sys::socket::{setsockopt, getsockopt};
5use queen_io::net::tcp::TcpStream;
6
7pub trait TcpExt: AsRawFd {
8 fn set_keep_alive(&self, enabled: bool) -> io::Result<()> {
9 let en: i32 = if enabled { 1 } else { 0 };
10
11 setsockopt(self.as_raw_fd(), libc::SOL_SOCKET, libc::SO_KEEPALIVE, en)
12 }
13
14 fn keep_alive(&self) -> io::Result<bool> {
15 let ret: i32 = getsockopt(self.as_raw_fd(), libc::SOL_SOCKET, libc::SO_KEEPALIVE)?;
16
17 if ret == 1 { Ok(true) } else { Ok(false) }
18 }
19
20 fn set_keep_idle(&self, secs: i32) -> io::Result<()> {
23 setsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPIDLE, secs)
24 }
25
26 fn keep_idle(&self) -> io::Result<i32> {
27 getsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPIDLE)
28 }
29
30 fn set_keep_intvl(&self, secs: i32) -> io::Result<()> {
35 setsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPINTVL, secs)
36 }
37
38 fn keep_intvl(&self) -> io::Result<i32> {
39 getsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPINTVL)
40 }
41
42 fn set_keep_cnt(&self, count: i32) -> io::Result<()> {
46 setsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPCNT, count)
47 }
48
49 fn keep_cnt(&self) -> io::Result<i32> {
50 getsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPCNT)
51 }
52}
53
54impl TcpExt for TcpStream {}