maborg
maborg

Reputation: 516

it's possible to change DNS programmatically on mac os?

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 )

Upvotes: 4

Views: 4011

Answers (2)

Gurjeet Singh
Gurjeet Singh

Reputation: 2807

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

Upvotes: 2

Robert Jordan
Robert Jordan

Reputation: 1103

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);
}

Upvotes: 7

Related Questions