Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding DNS server settings programmatically on Mac OS X

I have some cross platform DNS client code that I use for doing end to end SMTP and on windows I can find the current DNS server ip addresses by looking in the registry. On the Mac I can probably use the SystemConfiguration framework as mentioned in the first answer, however the exact method of doing so is not immediately obvious.

For instance SCDynamicStoreCopyDHCPInfo returns some of the dynamic DHCP related data but not the DNS server addresses.

like image 817
user33847 Avatar asked Nov 04 '08 01:11

user33847


1 Answers

I know its very late to answer this question but may be helpful for the others.

This Code will help out for this task ..

SCPreferencesRef prefsDNS = SCPreferencesCreate(NULL, CFSTR("DNSSETTING"), NULL);
CFArrayRef services = SCNetworkServiceCopyAll(prefsDNS);
long servicesCount = CFArrayGetCount(services);
for (long i = 0; i < servicesCount; i++) {
    const SCNetworkServiceRef service = (const SCNetworkServiceRef)CFArrayGetValueAtIndex(services, i);
    CFStringRef interfaceServiceID = SCNetworkServiceGetServiceID(service);
    CFStringRef primaryservicepath = CFStringCreateWithFormat(NULL,NULL,CFSTR("State:/Network/Service/%@/DNS"),interfaceServiceID);
    SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("DNSSETTING"), NULL, NULL);
    CFPropertyListRef propList = SCDynamicStoreCopyValue(dynRef,primaryservicepath);
    if (propList) {
        CFDictionaryRef dict = (CFDictionaryRef)propList;
        CFArrayRef addresses = (CFArrayRef)CFDictionaryGetValue(dict, CFSTR("ServerAddresses"));
        long addressesCount = CFArrayGetCount(addresses);
        for (long j = 0; j < addressesCount; j++) {
            CFStringRef address = (CFStringRef)CFArrayGetValueAtIndex(addresses, j);
            // Print address
            CFShow(address);
        }
        CFRelease(propList);
    }
    CFRelease(dynRef);
    CFRelease(primaryservicepath);
}
CFRelease(services);
CFRelease(prefsDNS);
like image 110
taha027 Avatar answered Oct 07 '22 12:10

taha027