vector/
net.rs

1//! Networking-related helper functions.
2
3use std::{io, time::Duration};
4
5use socket2::{SockRef, TcpKeepalive};
6use tokio::net::TcpStream;
7
8/// Sets the receive buffer size for a socket.
9///
10/// This is the equivalent of setting the `SO_RCVBUF` socket setting directly.
11///
12/// # Errors
13///
14/// If there is an error setting the receive buffer size on the given socket, or if the value given
15/// as the socket is not a valid socket, an error variant will be returned explaining the underlying
16/// I/O error.
17pub fn set_receive_buffer_size<'s, S>(socket: &'s S, size: usize) -> io::Result<()>
18where
19    SockRef<'s>: From<&'s S>,
20{
21    SockRef::from(socket).set_recv_buffer_size(size)
22}
23
24/// Sets the send buffer size for a socket.
25///
26/// This is the equivalent of setting the `SO_SNDBUF` socket setting directly.
27///
28/// # Errors
29///
30/// If there is an error setting the send buffer size on the given socket, or if the value given
31/// as the socket is not a valid socket, an error variant will be returned explaining the underlying
32/// I/O error.
33pub fn set_send_buffer_size<'s, S>(socket: &'s S, size: usize) -> io::Result<()>
34where
35    SockRef<'s>: From<&'s S>,
36{
37    SockRef::from(socket).set_send_buffer_size(size)
38}
39
40/// Sets the TCP keepalive behavior on a socket.
41///
42/// This is the equivalent of setting the `SO_KEEPALIVE` and `TCP_KEEPALIVE` socket settings
43/// directly.
44///
45/// # Errors
46///
47/// If there is an error with either enabling keepalive probes or setting the TCP keepalive idle
48/// timeout on the given socket, an error variant will be returned explaining the underlying I/O
49/// error.
50pub fn set_keepalive(socket: &TcpStream, ttl: Duration) -> io::Result<()> {
51    SockRef::from(socket).set_tcp_keepalive(&TcpKeepalive::new().with_time(ttl))
52}