可以在mac os上以编程方式更改DNS吗?

时间:2011-04-27 15:02:04

标签: macos dns

使用SystemConfiguration框架或其他框架的任何示例? (类似的问题Finding DNS server settings programmatically on Mac OS X有很混乱的答案)

2 个答案:

答案 0 :(得分:7)

我最近遇到了同样的问题。我在这里发布了我的解决方案:

http://blog.notampering.com/

这是片段......希望它有所帮助。

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

答案 1 :(得分:1)

此处记录了shell脚本版本:http://osxdaily.com/2015/06/02/change-dns-command-line-mac-os-x/

简称为:

# 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