get system release in rust

To get the system release (or operating system version) in Rust, we can use the std::env::consts::OS constant to check the current operating system and then use an appropriate method to obtain the version number. For example, on Unix-based systems, we can use the uname system call to get the system information, while on Windows we can use the GetVersion() function. Here's an example code snippet that demonstrates how to obtain the system release using Rust:

main.rs
use std::env;

fn main() {
    let os = env::consts::OS.to_lowercase(); // get current operating system
    
    let version = match os.as_str() {
        "linux" => {
            // Use uname system call to get release information on Unix-based systems
            let utsname = libc::utsname {
                sysname: [0; libc::UTSNAME_SYSNAME_LEN],
                nodename: [0; libc::UTSNAME_NODENAME_LEN],
                release: [0; libc::UTSNAME_RELEASE_LEN],
                version: [0; libc::UTSNAME_VERSION_LEN],
                machine: [0; libc::UTSNAME_MACHINE_LEN],
                domainname: [0; libc::UTSNAME_DOMAINNAME_LEN],
            };
            let r = unsafe { libc::uname(&mut utsname) };
            if r == 0 {
                // convert C-style string to Rust String and remove padding
                let release = String::from_utf8_lossy(&utsname.release)
                                .trim_end_matches('\0')
                                .to_string();
                release
            } else {
                "".to_string()
            }
        },
        "windows" => {
            // Use GetVersionEx() API call to get version information on Windows
            let os_version_info = winapi::um::sysinfoapi::OSVERSIONINFOEXW {
                dwOSVersionInfoSize: std::mem::size_of::<winapi::um::sysinfoapi::OSVERSIONINFOEXW>() as u32,
                ..Default::default()
            };
            let r = unsafe { winapi::um::sysinfoapi::GetVersionExW(
                                   &mut os_version_info as *mut winapi::um::sysinfoapi::OSVERSIONINFOEXW
                                )};
            if r != 0 {
                format!("{}.{}.{}", os_version_info.dwMajorVersion, os_version_info.dwMinorVersion, os_version_info.dwBuildNumber)
            } else {
                "".to_string()
            }
        },
        _ => "".to_string(),
    };
    
    println!("Operating System: {}, Release: {}", os, version);
}
1984 chars
48 lines

This code uses unsafe Rust code with some WinAPI and libc calls to obtain the system release information for different operating systems. Note that the unsafe block is required because these system level calls are inherently not safe but offer valuable functionality in specific scenarios.

related categories

gistlibby LogSnag