Elmi
Elmi

Reputation: 6193

Get HD/Partition serial number

When Using Windows I can get a (more or less unique) serial number of a HDD partition by using command

GetVolumeInformation()

My question: is there something similar available for Linux? Means a number that would change only when somebody formats a partition and that can be retrieved programmatically?

Thanks!

Upvotes: 1

Views: 1848

Answers (3)

abligh
abligh

Reputation: 25119

Partitions have (at least) three identities in linux:

  • The raw device identifier (think cat /proc/partitions) - this is not a unique serial number
  • The UUID of the partition - can be found with blkid, and stored within the partition itself. You can also manually parse /dev/.blkid.tab - the format being obvious.
  • The disk label - also stored within the partition. EG:
lsblk -o name,mountpoint,label,uuid
NAME   MOUNTPOINT LABEL UUID
sda
├─sda1 /                315eaf50-adcc-4f0d-b767-f008f3f1c194
├─sda2
└─sda5 [SWAP]           1ff31705-f488-44a4-ba5f-e2fe9eff4b96
sr0

Of these, the second is closest to what you want. To read it programatically, use libblkid.

Upvotes: 1

useraged
useraged

Reputation: 1716

You can use udev to get the serial number of the device. (You'll need to know the device name though)

struct udev *context = udev_new();
struct udev_device *device = udev_device_new_from_syspath(context, "/sys/block/sda");
const char *id = udev_device_get_property_value(device, "ID_SERIAL");
// Cleanup
udev_device_unref(device);
udev_unref(context);

Upvotes: 2

wojtow
wojtow

Reputation: 975

In linux, you could use the blkid command to get the UUID of the partition:

# blkid /dev/sda1
/dev/sda1: UUID="15677362-cef3-4a53-aca3-3bace1b0d92a" TYPE="ext4"

This info is stored in the formatting of specific partition types like ext4, xfs and changes when reformatted. There is no info available for unformatted partitions.

If you need to call it from code, calling out to a shell to run this command isn't exactly the prettiest way to do it, but it could work:

#include <stdio.h>

int main(int argc,char ** argv) {

  /* device you are looking for */   
  char device[]="/dev/sda1";

  /* buffer to hold info */
  char buffer[1024];

  /* format into a single command to be run */
  sprintf(buffer,"/sbin/blkid -o value %s",device);

  /* run the command via popen */
  FILE *f=popen(buffer,"r");

  /* probably should check to make sure f!=null */

  /* read the first line of output */
  fgets(buffer,sizeof(buffer),f);

  /* print the results (note, newline is included in string) */
  fprintf(stdout,"uuid is %s",buffer);

  }

Upvotes: 2

Related Questions