Skip to content

Commit 488441a

Browse files
bleggettThomasdezeeuw
authored andcommitted
Add support for getting SO_COOKIE socket option on linux
Signed-off-by: Benjamin Leggett <benjamin.leggett@solo.io>
1 parent 6713533 commit 488441a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/sys/unix.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2418,6 +2418,18 @@ impl crate::Socket {
24182418
unsafe { setsockopt(self.as_raw(), libc::SOL_SOCKET, libc::SO_DETACH_FILTER, 0) }
24192419
}
24202420

2421+
/// Gets the value for the `SO_COOKIE` option on this socket.
2422+
///
2423+
/// The socket cookie is a unique, kernel-managed identifier tied to each socket.
2424+
/// Therefore, there is no corresponding `set` helper.
2425+
///
2426+
/// For more information about this option, see [Linux patch](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5daab9db7b65df87da26fd8cfa695fb9546a1ddb)
2427+
#[cfg(all(feature = "all", any(target_os = "linux")))]
2428+
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", any(target_os = "linux")))))]
2429+
pub fn cookie(&self) -> io::Result<u64> {
2430+
unsafe { getsockopt::<libc::c_ulonglong>(self.as_raw(), libc::SOL_SOCKET, libc::SO_COOKIE) }
2431+
}
2432+
24212433
/// Get the value of the `IPV6_TCLASS` option for this socket.
24222434
///
24232435
/// For more information about this option, see [`set_tclass_v6`].

tests/socket.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1528,3 +1528,21 @@ fn dccp() {
15281528
let mut recv_buf = [0_u8; 64];
15291529
assert!(accepted.read(&mut recv_buf).unwrap() == msg.len());
15301530
}
1531+
1532+
#[test]
1533+
#[cfg(all(feature = "all", target_os = "linux"))]
1534+
fn cookie() {
1535+
let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap();
1536+
let first_socket_cookie = socket.cookie();
1537+
match first_socket_cookie {
1538+
Ok(_) => {}
1539+
Err(err) => panic!("Could not get socket cookie, err: {err}"),
1540+
}
1541+
1542+
//Fetch cookie again and make sure it's the same value (ALWAYS should be, smoke test)
1543+
let second_socket_cookie = socket.cookie();
1544+
match second_socket_cookie {
1545+
Ok(cookie) => assert_eq!(cookie, first_socket_cookie.unwrap()),
1546+
Err(err) => panic!("Could not get socket cookie a second time, err: {err}"),
1547+
}
1548+
}

0 commit comments

Comments
 (0)