summaryrefslogtreecommitdiff
path: root/vendor/system-configuration/examples/set_dns.rs
blob: 157063cfb36bd26a3dee9d8d0c90744d2d831d90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use core_foundation::{
    array::CFArray,
    base::{TCFType, ToVoid},
    dictionary::CFDictionary,
    propertylist::CFPropertyList,
    string::{CFString, CFStringRef},
};
use system_configuration::{
    dynamic_store::{SCDynamicStore, SCDynamicStoreBuilder},
    sys::schema_definitions::{kSCDynamicStorePropNetPrimaryService, kSCPropNetDNSServerAddresses},
};

// This example will change the DNS settings on the primary
// network interface to 8.8.8.8 and 8.8.4.4

fn main() {
    let store = SCDynamicStoreBuilder::new("my-test-dyn-store").build();
    let primary_service_uuid = get_primary_service_uuid(&store).expect("No PrimaryService active");
    println!("PrimaryService UUID: {}", primary_service_uuid);

    let primary_service_path = CFString::new(&format!(
        "State:/Network/Service/{}/DNS",
        primary_service_uuid
    ));
    println!("PrimaryService path: {}", primary_service_path);

    let dns_dictionary = create_dns_dictionary(&[
        CFString::from_static_string("8.8.8.8"),
        CFString::from_static_string("8.8.4.4"),
    ]);

    let success = store.set(primary_service_path, dns_dictionary);
    println!("success? {}", success);
}

fn get_primary_service_uuid(store: &SCDynamicStore) -> Option<CFString> {
    let dictionary = store
        .get("State:/Network/Global/IPv4")
        .and_then(CFPropertyList::downcast_into::<CFDictionary>)?;
    dictionary
        .find(unsafe { kSCDynamicStorePropNetPrimaryService }.to_void())
        .map(|ptr| unsafe { CFString::wrap_under_get_rule(*ptr as CFStringRef) })
}

fn create_dns_dictionary(addresses: &[CFString]) -> CFDictionary {
    let key = unsafe { CFString::wrap_under_get_rule(kSCPropNetDNSServerAddresses) };
    let value = CFArray::from_CFTypes(addresses);
    let typed_dict = CFDictionary::from_CFType_pairs(&[(key, value)]);
    unsafe { CFDictionary::wrap_under_get_rule(typed_dict.as_concrete_TypeRef()) }
}