Skip to content

Commit 07c7b37

Browse files
elmarcoThomasdezeeuw
authored andcommitted
unix: add SockAddr::vsock_address()
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
1 parent f424722 commit 07c7b37

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/sys/unix.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -463,8 +463,20 @@ impl SockAddr {
463463
}
464464
.map(|(_, addr)| addr)
465465
}
466-
}
467466

467+
/// Returns this address VSOCK CID/port if it is in the `AF_VSOCK` family,
468+
/// otherwise return `None`.
469+
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
470+
pub fn vsock_address(&self) -> Option<(u32, u32)> {
471+
if self.family() == libc::AF_VSOCK as sa_family_t {
472+
// Safety: if the ss_family field is AF_VSOCK then storage must be a sockaddr_vm.
473+
let addr = unsafe { &*(self.as_ptr() as *const libc::sockaddr_vm) };
474+
Some((addr.svm_cid, addr.svm_port))
475+
} else {
476+
None
477+
}
478+
}
479+
}
468480

469481
pub(crate) type Socket = c_int;
470482

tests/socket.rs

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ fn socket_address_vsock() {
141141
let addr = SockAddr::vsock(1, 9999).unwrap();
142142
assert!(addr.as_socket_ipv4().is_none());
143143
assert!(addr.as_socket_ipv6().is_none());
144+
assert_eq!(addr.vsock_address().unwrap(), (1, 9999));
144145
}
145146

146147
#[test]

0 commit comments

Comments
 (0)