gimmeamilk
gimmeamilk

Reputation: 2120

How can I generate system-wide unique IDs under Linux

I'm working on a multiprocess Linux system and need to generate unique IDs. Security is not a consideration, so an ID generator that starts at zero and counts up would be fine. Also it's just within a local machine, no network involved. Obviously it's not hard to implement this, but I was just wondering if there was anything already provided (preferably lightweight).

Upvotes: 9

Views: 13156

Answers (4)

fredk
fredk

Reputation: 328

In cases where uuidgen is not installed you can use mktemp. For example, for 16 characters (should be enough to achieve system-wide unique IDs) ...

mktemp -u XXXXXXXXXXXXXXXX

Upvotes: 1

PodTech.io
PodTech.io

Reputation: 5264

Also useful..

 cat /etc/machine-id

The /etc/machine-id file contains the unique machine ID of the local system that is set during installation. The machine ID is a single newline-terminated, hexadecimal, 32-character, lowercase machine ID string. When decoded from hexadecimal, this corresponds with a 16-byte/128-bit string.

Upvotes: 0

johnsyweb
johnsyweb

Reputation: 141998

This sounds like a job for... ...uuidgen:

% uuidgen 
975DA04B-9A5A-4816-8780-C051E37D1414

If you want to build it into your own application or service, you'll need libuuid:

#include <uuid/uuid.h>
#include <iostream>

int main()
{
    uuid_t uu;
    uuid_generate(uu);
    char uuid[37];
    uuid_unparse(uu, uuid);
    std::cout << uuid << std::endl;
}

Upvotes: 20

Alex Howansky
Alex Howansky

Reputation: 53646

There is a command line tool called uuid that will do exactly what you want. I'm not sure if it gets installed by default in various distributions though, so you may have to do that yourself.

Upvotes: 1

Related Questions