Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

macos

dns

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 )

like image 290
maborg Avatar asked Jan 20 '23 21:01

maborg


1 Answers

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);
}
like image 82
Robert Jordan Avatar answered Jan 31 '23 05:01

Robert Jordan