Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a program to list all the USB devices in a Mac?

Tags:

I have a limited exposure to the Mac OS X operating system and now I have started using Xcode and am studying about I/O kit. I need to create a program in Xcode under command line tool in order to list all USB devices connected in a Mac system. Those who have previous experience under this, please help me. If anyone could provide me with sample code then it will be of great use, as I am looking for starting point.

like image 661
Dili Avatar asked Sep 27 '11 10:09

Dili


People also ask

How do I find Hardware devices on my Mac?

To open a system report, choose Apple menu > About This Mac, then click System Report. Tip: You can also press and hold the Option key, then choose Apple menu > System Information. To change your view of the report, do one of the following: See a longer report: Choose File > Show More Information.


1 Answers

You can adapt USBPrivateDataSample to your needs, the sample sets up a notifier, lists the currently attached devices, then waits for device attach/detach. If you do, you will want to remove the usbVendor and usbProduct matching dictionaries, so all USB devices are matched.

Alternately, you can use IOServiceGetMatchingServices to get an iterator for all current matching services, using a dictionary created by IOServiceMatching(kIOUSBDeviceClassName).

Here's a short sample (which I've never run):

#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>

int main(int argc, const char *argv[])
{
    CFMutableDictionaryRef matchingDict;
    io_iterator_t iter;
    kern_return_t kr;
    io_service_t device;

    /* set up a matching dictionary for the class */
    matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
    if (matchingDict == NULL)
    {
        return -1; // fail
    }

    /* Now we have a dictionary, get an iterator.*/
    kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
    if (kr != KERN_SUCCESS)
    {
        return -1;
    }

    /* iterate */
    while ((device = IOIteratorNext(iter)))
    {
        /* do something with device, eg. check properties */
        /* ... */
        /* And free the reference taken before continuing to the next item */
        IOObjectRelease(device);
    }

   /* Done, release the iterator */
   IOObjectRelease(iter);
   return 0;
}
like image 190
Hasturkun Avatar answered Oct 17 '22 02:10

Hasturkun