Pregunta

desarrollo de Mac OS X es un nuevo animal bastante para mí, y estoy en el proceso de portar más de un cierto software. Para la concesión de licencias de software y el registro que necesito para ser capaz de generar algún tipo de identificador de hardware. No tiene que ser algo de fantasía; dirección MAC de Ethernet, serie del disco duro, serie de la CPU, algo por el estilo.

He y mucho más en Windows, pero no tienen ni idea en Mac. Cualquier idea de lo que tengo que hacer, o donde puedo ir para obtener información sobre esto sería genial!

Editar:

Para cualquier otra persona que esté interesada en esto, este es el código que terminé usando con la clase QProcess de Qt:

QProcess proc;

QStringList args;
args << "-c" << "ioreg -rd1 -c IOPlatformExpertDevice |  awk '/IOPlatformUUID/ { print $3; }'";
proc.start( "/bin/bash", args );
proc.waitForFinished();

QString uID = proc.readAll();

Nota:. Estoy usando C ++

¿Fue útil?

Solución

Prueba este comando en el terminal:

ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { split($0, line, "\""); printf("%s\n", line[4]); }'

aquí

Aquí es ese comando envuelto en Cacao (que probablemente se podría hacer un poco más limpio):

NSArray * args = [NSArray arrayWithObjects:@"-rd1", @"-c", @"IOPlatformExpertDevice", @"|", @"grep", @"model", nil];
NSTask * task = [NSTask new];
[task setLaunchPath:@"/usr/sbin/ioreg"];
[task setArguments:args];

NSPipe * pipe = [NSPipe new];
[task setStandardOutput:pipe];
[task launch];

NSArray * args2 = [NSArray arrayWithObjects:@"/IOPlatformUUID/ { split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }", nil];
NSTask * task2 = [NSTask new];
[task2 setLaunchPath:@"/usr/bin/awk"];
[task2 setArguments:args2];

NSPipe * pipe2 = [NSPipe new];
[task2 setStandardInput:pipe];
[task2 setStandardOutput:pipe2];
NSFileHandle * fileHandle2 = [pipe2 fileHandleForReading];
[task2 launch];

NSData * data = [fileHandle2 readDataToEndOfFile];
NSString * uuid = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Otros consejos

Para C / C ++:

void get_platform_uuid(char * buf, int bufSize) {
    io_registry_entry_t ioRegistryRoot = IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/");
    CFStringRef uuidCf = (CFStringRef) IORegistryEntryCreateCFProperty(ioRegistryRoot, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, 0);
    IOObjectRelease(ioRegistryRoot);
    CFStringGetCString(uuidCf, buf, bufSize, kCFStringEncodingMacRoman);
    CFRelease(uuidCf);    
}

¿Por qué no tratar gethostuuid()? Aquí está la documentación del sistema Mac OS X llamadas Manual:

Nombre:

 gethostuuid -- return a unique identifier for the current machine

SINOPSIS:

 #include <unistd.h>

 int gethostuuid(uuid_t id, const struct timespec *wait);

Descripción:

  

La función gethostuuid () devuelve un uuid_t de 16 bytes especificado por ID, que identifica de forma única la máquina actual. Tenga en cuenta que los identificadores de hardware que gethostuuid () utiliza para generar el UUID puede sí ser modificado.

     

El argumento de espera es un puntero a una estructura timespec que especifica el tiempo máximo de espera para el resultado. Ajuste de la tv_sec y campos tv_nsec a cero significa que esperar indefinidamente hasta que se complete.

VALORES DE RETORNO:

  

La función gethostuuid () devuelve cero en caso de éxito o -1 en caso de error.

ERRORES

  

El gethostuuid () falla si funciones:

 [EFAULT]           wait points to memory that is not a valid part of the
                    process address space.

 [EWOULDBLOCK]      The wait timeout expired before the UUID could be
                    obtained.

Esto sería más fácil de responder si usted nos dijo qué idioma que estaba utilizando. La información se puede obtener sin ningún tipo de comandos de shell a través del marco SystemConfiguration, y también a través IOKit si usted quiere conseguir sus manos muy sucias.

- (NSString*) getMACAddress: (BOOL)stripColons {
    NSMutableString         *macAddress         = nil;
    NSArray                 *allInterfaces      = (NSArray*)SCNetworkInterfaceCopyAll();
    NSEnumerator            *interfaceWalker    = [allInterfaces objectEnumerator];
    SCNetworkInterfaceRef   curInterface        = nil;

    while ( curInterface = (SCNetworkInterfaceRef)[interfaceWalker nextObject] ) {
        if ( [(NSString*)SCNetworkInterfaceGetBSDName(curInterface) isEqualToString:@"en0"] ) {
            macAddress = [[(NSString*)SCNetworkInterfaceGetHardwareAddressString(curInterface) mutableCopy] autorelease];

            if ( stripColons == YES ) {
                [macAddress replaceOccurrencesOfString: @":" withString: @"" options: NSLiteralSearch range: NSMakeRange(0, [macAddress length])];
            }

            break;
        }
    }

    return [[macAddress copy] autorelease];
}
/*
g++ mac_uuid.cpp -framework CoreFoundation -lIOKit
*/


#include <iostream>
#include <IOKit/IOKitLib.h>

using namespace std;

void get_platform_uuid(char * buf, int bufSize)
{
   io_registry_entry_t ioRegistryRoot = IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/");
   CFStringRef uuidCf = (CFStringRef) IORegistryEntryCreateCFProperty(ioRegistryRoot, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, 0);
   IOObjectRelease(ioRegistryRoot);
   CFStringGetCString(uuidCf, buf, bufSize, kCFStringEncodingMacRoman);
   CFRelease(uuidCf);
}

int main()
{
   char buf[512] = "";
   get_platform_uuid(buf, sizeof(buf));
   cout << buf << endl;
}

En funcionamiento:

system_profiler | grep 'Serial Number (system)'

en un terminal devuelve lo que es probable que un identificador único. Eso funciona en mi caja de 10.5, no estoy seguro de lo que la cadena correcta será en otras versiones de OS X.

Como algunas personas han insinuado anteriormente, se puede utilizar un comando de terminal para obtener un identificador de hardware.

Asumo que quieres hacer esto en código sin embargo, así que echar un vistazo a la clase NSTask en Cocoa. Básicamente le permite ejecutar comandos de terminal dentro de su aplicación.

Este código es un ejemplo de cómo utilizar NSTask en Cocoa. Se configura el entorno para ejecutar el comando "killall". Se pasa el argumento "Finder".

Es la equivilent de correr "killall Finder" en la línea de comandos, que matará el Finder obviamente.

NSTask *aTask = [[NSTask alloc] init];
NSMutableArray *args = [NSMutableArray array];

[aTask setLaunchPath: @"/usr/bin/killall"];
[args addObject:[@"/Applications/Finder" lastPathComponent]];
[aTask setArguments:args];
[aTask launch];

[aTask release];

Perfil de Sistema (en Aplicaciones - Utilidades) contiene la mayoría de este tipo de información. Que tiene el número de serie y la dirección MAC (sin relación con Mac. Todos los equipos tienen una dirección MAC que es casi único a cada tarjeta de red).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top