Rust Program to Determine the name and version of the operating system


Determine the name and version of the operating system

Rust Programming Language


Determine the name and version of the operating system


Problem


Rust program that determines the name and version of the operating system.

Input


#[cfg(target_os = "linux")]
fn main() {
    let uname = nix::sys::utsname::uname();
    let os_name = std::str::from_utf8(&uname.sysname).unwrap();
    let os_release = std::str::from_utf8(&uname.release).unwrap();
    println!("OS: {} {}", os_name, os_release);
}

#[cfg(target_os = "windows")]
fn main() {
    use winreg::enums::*;
    use winreg::RegKey;

    let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
    let subkey = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
    let digital_product_id = hklm.open_subkey(subkey)
        .unwrap()
        .get_value("DigitalProductId")
        .unwrap();
    let os_name = "Windows";
    let os_version = digital_product_id[14..16].to_vec();
    let os_version = os_version.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<String>>()
        .join(".");
    println!("OS: {} {}", os_name, os_version);
}{codeBox}


Output


When run on a Linux machine, this program might output something like the following:

OS: Linux 5.11.0-27-generic{codeBox}

When run on a Windows machine, this program might output something like the following:

OS: Windows 10.0{codeBox}


Explanation


This program uses different code depending on the target operating system. If the target OS is Linux, the program uses the nix crate to get information about the operating system. Specifically, it uses the uname() function from the sys::utsname module to get a UtsName struct containing information about the operating system, and then extracts the system name and release version from that struct.

If the target OS is Windows, the program uses the winreg crate to get information about the operating system. Specifically, it opens the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion registry key, and retrieves the DigitalProductId value, which contains information about the operating system version. It then extracts the version number from this value.

Post a Comment