Skip to content

Instantly share code, notes, and snippets.

@loderunner
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loderunner/6ee86e2f0236ecb807fd to your computer and use it in GitHub Desktop.
Save loderunner/6ee86e2f0236ecb807fd to your computer and use it in GitHub Desktop.
// GetHostName.c
//
// Prints current host's name in localized, human-readable format to stdout
//
// Compile using:
// cc -framework SystemConfiguration -framework CoreFoundation -o GetHostName GetHostName.c
//
#include <SystemConfiguration/SystemConfiguration.h>
#define f_strdup strdup
char * GetHostName()
{
SCPreferencesRef prefs = SCPreferencesCreate(NULL, CFSTR("GetHostName"), NULL); // Get system preferences handle, arg2=calling process name
Boolean success = SCPreferencesLock(prefs, TRUE); // arg2: TRUE = wait for lock
// TODO: check lock or proceed without locking
CFDictionaryRef systemPreferences = SCPreferencesGetValue(prefs, CFSTR("System")); // Get "System" properties
CFDictionaryRef systemDict = CFDictionaryGetValue(systemPreferences, CFSTR("System")); // Get "System" dictionary (from "System" properties... I know.)
CFStringRef hostName = CFDictionaryGetValue(systemDict, CFSTR("ComputerName"));
success = SCPreferencesUnlock(prefs);
const char * hostNameCString = CFStringGetCStringPtr(hostName, kCFStringEncodingUTF8); // Convert to UTF-8 const char *
// This function [CFStringGetCStringPtr] either returns the requested pointer immediately
// with no memory allocations and no copying, in constant time, or returns NULL.
//
// TODO: if CFStringGetCStringPtr returns NULL, use slower CFStringGetCString
CFRelease(prefs); // Release system preferences handle
return f_strdup(hostNameCString);
}
int main(int argc, char** argv)
{
char * hostName = GetHostName();
printf("%s\n", hostName);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment