Last active
July 26, 2023 03:22
-
-
Save leiless/5dddcdfbb1d578bd96c44ff727b2cc05 to your computer and use it in GitHub Desktop.
Finding DNS server addresses programmatically on macOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finding DNS server addresses programmatically on macOS | |
* see: | |
* https://stackoverflow.com/questions/260518/finding-dns-server-settings-programmatically-on-mac-os-x | |
*/ | |
#import <Foundation/Foundation.h> | |
#import <SystemConfiguration/SystemConfiguration.h> | |
int main(void) { | |
CFStringRef callerName = CFSTR("foobar"); | |
SCPreferencesRef scPrefs = SCPreferencesCreate(NULL, callerName, NULL); | |
CFArrayRef services = SCNetworkServiceCopyAll(scPrefs); | |
if (services) { | |
CFIndex count = CFArrayGetCount(services); | |
for (CFIndex i = 0; i < count; i++) { | |
NSLog(@"> i = %ld", i); | |
SCNetworkServiceRef service = CFArrayGetValueAtIndex(services, i); | |
SCNetworkInterfaceRef interface = SCNetworkServiceGetInterface(service); | |
NSLog(@"%@", interface); | |
NSString *interfaceServiceID = (__bridge NSString *) SCNetworkServiceGetServiceID(service); | |
CFStringRef primaryServicePath = CFStringCreateWithFormat(NULL, NULL, CFSTR("State:/Network/Service/%@/DNS"), interfaceServiceID); | |
NSLog(@"%@", primaryServicePath); | |
SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, callerName, NULL, NULL); | |
CFDictionaryRef dnskey = SCDynamicStoreCopyValue(dynRef, primaryServicePath); | |
// dnskey will give you the DNS server address. | |
NSLog(@"DNS dict: %@", dnskey); | |
} | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Other commands