Skip to content

Instantly share code, notes, and snippets.

@csexton
Created June 27, 2019 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csexton/56121dbb613df68f143162b60a2c694a to your computer and use it in GitHub Desktop.
Save csexton/56121dbb613df68f143162b60a2c694a to your computer and use it in GitHub Desktop.
Get the USB Serial Number from C in Go with IOKit
package main
// #cgo LDFLAGS: -framework CoreFoundation -framework IOKit
// #include <CoreFoundation/CoreFoundation.h>
// #include <IOKit/IOKitLib.h>
// #include <IOKit/serial/IOSerialKeys.h>
// #include <IOKit/usb/IOUSBLib.h>
//
// const char *
// getSerialNumber()
// {
// CFMutableDictionaryRef matching = IOServiceMatching("IOPlatformExpertDevice");
// io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, matching);
// CFStringRef serialNumber = IORegistryEntryCreateCFProperty(service,
// CFSTR("IOPlatformSerialNumber"), kCFAllocatorDefault, 0);
// const char *str = CFStringGetCStringPtr(serialNumber, kCFStringEncodingUTF8);
// IOObjectRelease(service);
//
// return str;
// }
//
// static void printKeys (const void* key, const void* value, void* context) {
// CFShow(key);
// }
//
// void myIoKit() {
// printf("hi\n");
// CFMutableDictionaryRef keywordDict = IOServiceMatching(kIOSerialBSDServiceValue);
// io_object_t port = 0;
// io_iterator_t iterator = 0;
// kern_return_t result = IOServiceGetMatchingServices(kIOMasterPortDefault, keywordDict, &iterator);
// if (result) {
// exit(EXIT_FAILURE);
// }
//
// while ((port = IOIteratorNext(iterator))) {
// CFMutableDictionaryRef dict = NULL;
// result = IORegistryEntryCreateCFProperties(port, &dict, kCFAllocatorDefault, 0);
//
// io_object_t parent = 0;
// io_object_t parents = port;
// while (KERN_SUCCESS == IORegistryEntryGetParentEntry(parents, kIOServicePlane, &parent)) {
// result = IORegistryEntryCreateCFProperties(parent, &dict, kCFAllocatorDefault, 0);
//
// if (parents != port)
// IOObjectRelease(parents);
// parents = parent;
// }
//
// printf("0x%08lx", (uintptr_t)port);
// CFShow(dict);
// /*
// CFDictionaryApplyFunction(dict, printKeys, NULL);
// CFStringRef tmpString = CFDictionaryGetValue(dict, CFSTR("IOBluetoothActive"));
// NSLog(@"
// */
// printf("\n\n");
// }
// }
import "C"
import (
"fmt"
)
func main() {
C.myIoKit()
serialNumber := C.GoString(C.getSerialNumber())
fmt.Println(serialNumber)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment