4

Any example using the the SystemConfiguration framework or other frameworks ? (similar question Finding DNS server settings programmatically on Mac OS X has quite confusing answers )

Community
  • 1
  • 1
maborg
  • 435
  • 5
  • 24

2 Answers2

7

I recently had the same issue. I posted my solution here:

http://blog.notampering.com/

Here's the snippet... hope it helps.

#include <stdio.h>
#include <SystemConfiguration/SCPreferences.h>
#include <SystemConfiguration/SCDynamicStore.h>


int main (int argc, const char * argv[])
{
    //get current values
    SCDynamicStoreRef dynRef=SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("iked"), NULL, NULL);
CFDictionaryRef ipv4key = SCDynamicStoreCopyValue(dynRef,CFSTR("State:/Network/Global/IPv4"));
CFStringRef primaryserviceid = CFDictionaryGetValue(ipv4key,CFSTR("PrimaryService"));
CFStringRef primaryservicepath = CFStringCreateWithFormat(NULL,NULL,CFSTR("State:/Network/Service/%@/DNS"),primaryserviceid);
CFDictionaryRef dnskey = SCDynamicStoreCopyValue(dynRef,primaryservicepath);

//create new values
CFMutableDictionaryRef newdnskey = CFDictionaryCreateMutableCopy(NULL,0,dnskey);
CFDictionarySetValue(newdnskey,CFSTR("DomainName"),CFSTR("example.com"));

CFMutableArrayRef dnsserveraddresses = CFArrayCreateMutable(NULL,0,NULL);
CFArrayAppendValue(dnsserveraddresses, CFSTR("8.8.8.8"));
CFArrayAppendValue(dnsserveraddresses, CFSTR("4.2.2.2"));
CFDictionarySetValue(newdnskey, CFSTR("ServerAddresses"), dnsserveraddresses);

//set values
bool success = SCDynamicStoreSetValue(dynRef, primaryservicepath, newdnskey);

//clean up
CFRelease(dynRef);
CFRelease(primaryservicepath);
CFRelease(dnskey);
CFRelease(dnsserveraddresses);
CFRelease(newdnskey);
}
Alex Terente
  • 12,006
  • 5
  • 51
  • 71
Robert Jordan
  • 1,053
  • 1
  • 10
  • 17
  • 1
    This code is not working for me :(. SCDynamicStoreSetValue() returns false. – Omkar May 20 '15 at 17:41
  • Are you running it as root? – dgatwood Jul 02 '15 at 18:16
  • 1
    Yes must be running as root, and at least on my environment I needed to add: #include at the top to compile. – Meir Gerenstadt Aug 23 '16 at 13:49
  • For me, line: CFDictionaryRef dnskey = SCDynamicStoreCopyValue(dynRef,primaryservicepath); gives a casting error: Cannot initialize a variable of type 'CFDictionaryRef' (aka 'const __CFDictionary *') with an rvalue of type 'CFPropertyListRef _Nullable' (aka 'const void *') – Matt Cobb Jun 07 '18 at 19:07
2

The shell-script version is documented here: http://osxdaily.com/2015/06/02/change-dns-command-line-mac-os-x/

The short version is:

# Template:
networksetup -setdnsservers (Network Service) (DNS IP) (DNS IP) ...

# Example: set DNS for Wi-Fi to 8.8.8.8  8.8.4.4  1.1.1.1
sudo networksetup -setdnsservers Wi-Fi  8.8.8.8  8.8.4.4  1.1.1.1

# Example: Clear the manually assigned DNS so that the default values can take over
sudo networksetup -setdnsservers Wi-Fi  Empty
Gurjeet Singh
  • 2,635
  • 2
  • 27
  • 22