How to clear/flush the DNS cache? (Windows)

OK, this wasn’t quite so bad, particularly since the Clear method doesn’t take any parameters, apart from that monstrous CoInitializeSecurity() function call that I just copied from Microsoft’s documentation:

use windows::core::BSTR;
use windows::Win32::System::Com::*;
use windows::Win32::System::Wmi::{IWbemLocator, WbemLocator};

fn clear_dns_cache() -> windows::core::Result<()> {
    let namespace = BSTR::from(r"root/StandardCimv2");
    let dns_client_cache = BSTR::from("MSFT_DNSClientCache");
    let clear = BSTR::from("Clear");
    unsafe {
        let loc: IWbemLocator = CoCreateInstance(&WbemLocator, None, CLSCTX_INPROC_SERVER)?;
        let svc = loc.ConnectServer(&namespace, None, None, None, 0, None, None)?;
        svc.ExecMethod(&dns_client_cache, &clear, 0, None, None, None, None)
    }
}

fn main() {
    unsafe {
        CoInitializeEx(None, COINIT_MULTITHREADED).expect("CoInitializeEx failed unexpectedly");
        CoInitializeSecurity(
            None,
            -1,
            None,
            None,
            RPC_C_AUTHN_LEVEL_DEFAULT,
            RPC_C_IMP_LEVEL_IMPERSONATE,
            None,
            EOAC_NONE,
            None,
        )
        .expect("CoInitializeSecurity failed unexpectedly");
    }
    if let Err(e) = clear_dns_cache() {
        eprintln!("WMI error: {}", e);
    }
}
4 Likes