Skip to content

Commit

Permalink
Add Socket::(set_)recv_tos
Browse files Browse the repository at this point in the history
Gets or set the IP_RECVTOS option.
  • Loading branch information
JoNil committed Apr 26, 2022
1 parent 5436228 commit 040769b
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/socket.rs
Expand Up @@ -1388,6 +1388,52 @@ impl Socket {
getsockopt::<c_int>(self.as_raw(), sys::IPPROTO_IP, sys::IP_TOS).map(|tos| tos as u32)
}
}

/// Set the value of the `IP_RECVTOS` option for this socket.
///
/// If enabled, the IP_TOS ancillary message is passed with
/// incoming packets. It contains a byte which specifies the
/// Type of Service/Precedence field of the packet header.
#[cfg(not(any(
target_os = "fuschia",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
target_os = "windows",
)))]
pub fn set_recv_tos(&self, recv_tos: bool) -> io::Result<()> {
let recv_tos = if recv_tos { 1 } else { 0 };

unsafe {
setsockopt(
self.as_raw(),
sys::IPPROTO_IP,
sys::IP_RECVTOS,
recv_tos as c_int,
)
}
}

/// Get the value of the `IP_RECVTOS` option for this socket.
///
/// For more information about this option, see [`set_recv_tos`].
///
/// [`set_recv_tos`]: Socket::set_recv_tos
#[cfg(not(any(
target_os = "fuschia",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
target_os = "windows",
)))]
pub fn recv_tos(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), sys::IPPROTO_IP, sys::IP_RECVTOS)
.map(|recv_tos| recv_tos > 0)
}
}
}

/// Socket options for IPv6 sockets, get/set using `IPPROTO_IPV6`.
Expand Down
8 changes: 8 additions & 0 deletions src/sys/unix.rs
Expand Up @@ -77,6 +77,14 @@ pub(crate) use libc::{MSG_TRUNC, SO_OOBINLINE};
// Used in `Socket`.
#[cfg(all(feature = "all", not(target_os = "redox")))]
pub(crate) use libc::IP_HDRINCL;
#[cfg(not(any(
target_os = "fuschia",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
)))]
pub(crate) use libc::IP_RECVTOS;
#[cfg(not(any(
target_os = "fuschia",
target_os = "redox",
Expand Down
11 changes: 11 additions & 0 deletions tests/socket.rs
Expand Up @@ -1172,6 +1172,17 @@ test!(IPv4 ttl, set_ttl(40));
target_os = "illumos",
)))]
test!(IPv4 tos, set_tos(96));

#[cfg(not(any(
target_os = "fuschia",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
target_os = "windows",
)))]
test!(IPv4 recv_tos, set_recv_tos(true));

#[cfg(not(windows))] // TODO: returns `WSAENOPROTOOPT` (10042) on Windows.
test!(IPv4 broadcast, set_broadcast(true));

Expand Down

0 comments on commit 040769b

Please sign in to comment.