Pergunta

Mac OS X desenvolvimento é um relativamente novo animal para mim, e eu estou no processo de portar sobre algum software. Para o licenciamento de software e registro eu preciso ser capaz de gerar algum tipo de identificação de hardware. Ele não tem que ser algo extravagante; endereço MAC Ethernet, serial disco rígido, serial CPU, algo assim.

Eu tenho que cobria no Windows, mas eu não tenho uma pista sobre Mac. Qualquer idéia do que eu preciso fazer, ou onde eu posso ir para obter informações sobre isso seria ótimo!

Editar:

Para qualquer outra pessoa que está interessado nisso, este é o código que eu acabei usando com classe QProcess do 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:. Eu estou usando C ++

Foi útil?

Solução

Tente este comando Terminal:

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

A partir aqui

Aqui é que comando envolto em Cocoa (que provavelmente poderia ser feito um pouco mais limpo):

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];

Outras dicas

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 que não tentar gethostuuid()? Aqui está a documentação do OS X Sistema Mac chamadas Manual:

NOME:

 gethostuuid -- return a unique identifier for the current machine

Sinopse:

 #include <unistd.h>

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

Descrição:

O gethostuuid () função retorna um de 16 bytes uuid_t especificado por id, que identifica unicamente o equipamento actual. Esteja ciente de que os identificadores de hardware que gethostuuid () usa para gerar o UUID si pode ser modificado.

O argumento de espera é um ponteiro para um struct timespec que especifica o tempo máximo de espera para o resultado. Definir o tv_sec e campos tv_nsec a zero significa esperar indefinidamente até que ela seja concluída.

Os valores de retorno:

O gethostuuid () função retorna zero em caso de sucesso ou -1 em caso de erro.

ERROS

O gethostuuid () funções falhar se:

 [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.

Este seria mais fácil de resposta se você nos disse que língua você estava usando. A informação é obtida sem quaisquer comandos shell através do quadro SystemConfiguration, e também através IOKit se você quiser começar suas mãos realmente sujo.

- (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;
}

corrente:

system_profiler | grep 'Serial Number (system)'

em uma retornos de terminal que é provável uma identificação única. Que funciona em minha caixa de 10,5, eu não tenho certeza do que a seqüência correta será em outras versões do OS X.

Como algumas pessoas acima têm sugerido, você pode usar um comando Terminal para obter uma ID de hardware.

Eu suponho que você quer fazer isso no código no entanto por isso gostaria de dar uma olhada na classe NSTask em Cocoa. Ele basicamente permite que você execute comandos do terminal dentro de sua aplicação.

Este código é um exemplo de como usar NSTask no Cacau. Ele configura o ambiente para executar o comando "killall". Passa-se o argumento "Finder".

É o equivilent de correr "killall Finder" na linha de comando, que vai matar o localizador 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];

System Profiler (em Aplicativos - Utilitários) contém a maior parte deste tipo de informação. Ele tem o seu número de série e o endereço MAC (nenhuma relação com Mac. Todos os computadores têm um endereço MAC que é praticamente único para cada placa de rede).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top