Search code examples
cocoablockdevicensurlblock-device

Get block device from NSURL


The question says it all. How can I get the block device from an NSURL representing, for example, a removable media? What I would like to get from /Volumes/MyDevice is something like /dev/disk2. I wonder if that is possible without using the IOKit framework! Any help is appreciated.


Solution

  • DiskArbitration.framework will get you there:

    NSURL *volumeURL = [NSURL fileURLWithPath:@"/Volumes/YourDisk"];
    
    DASessionRef session = DASessionCreate(kCFAllocatorDefault);
    DADiskRef disk = DADiskCreateFromVolumePath(kCFAllocatorDefault,
                                                session,
                                                (__bridge CFURLRef)volumeURL);
    
    NSDictionary *desc = CFBridgingRelease(DADiskCopyDescription(disk));
    
    /* See DADisk.h for a list of available keys */
    NSLog(@"%@", desc[(NSString *)kDADiskDescriptionMediaBSDNameKey]);
    
    CFRelease(disk);
    CFRelease(session);
    

    As will statfs(2):

    struct statfs s;
    statfs([[volumeURL path] fileSystemRepresentation], &s);
    printf("%s\n", s.f_mntfromname);