Thread: How to get harddisk serial number without root access Linux, C

  1. #1
    Registered User
    Join Date
    Mar 2017
    Posts
    6

    How to get harddisk serial number without root access Linux, C

    I need to get hard disk serial number in normal user mode Linux using C. I've found some ways. However for all those need sudo (root) access. Any suggestions. Thanks

    Some findings: (however this should run as root)
    Code:
    static struct hd_driveid hd;
    int fd;
    
    if ((fd = open("/dev/hda", O_RDONLY | O_NONBLOCK)) < 0) {
        printf("ERROR opening /dev/hda\n");
        exit(1);
    }
    
    if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {
        printf("%.20s\n", hd.serial_no);
    } else if (errno == -ENOMSG) {
        printf("No serial number available\n");
    } else {
        perror("ERROR: HDIO_GET_IDENTITY");
        exit(1);
    }

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Take a look at the output of ls -l /dev/disk/by-id

    Another possibility:
    Code:
    #define _BSD_SOURCE
    #include <stdio.h>
    #include <string.h>
    
    #define DEVICE "sda"
    
    int main(void) {
        char buf[1000];
    
        FILE *f = popen("udevadm info --query=all --name=/dev/"
                        DEVICE
                        " | grep ID_SERIAL=", "r");
        fgets(buf, sizeof buf, f);
        pclose(f);
    
        buf[strcspn(buf, "\n")] = 0;
        printf("%s\n", buf+13);
    
        return 0;
    }
    Last edited by algorism; 04-11-2017 at 10:59 AM.

  3. #3
    Registered User
    Join Date
    Mar 2017
    Posts
    6
    Thanks a lot, I was looking for same kind of method everywhere. Your solution worked. Thanks again.
    However can you explain for what this macro is used for?
    #define _BSD_SOURCE

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Quote Originally Posted by inckka View Post
    Thanks a lot, I was looking for same kind of method everywhere. Your solution worked. Thanks again.
    However can you explain for what this macro is used for?
    #define _BSD_SOURCE
    Feature Test Macros

  5. #5
    Registered User
    Join Date
    Mar 2017
    Posts
    6
    Quote Originally Posted by algorism View Post
    Great. Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getting model an serial information from SAS harddisk
    By thomas23 in forum Linux Programming
    Replies: 13
    Last Post: 02-23-2014, 04:59 PM
  2. getting model an serial information from SAS harddisk
    By thomas23 in forum C Programming
    Replies: 2
    Last Post: 02-15-2014, 09:10 PM
  3. Replies: 4
    Last Post: 10-20-2010, 10:18 PM
  4. Equivalent to volume serial number in linux
    By Elkvis in forum Linux Programming
    Replies: 8
    Last Post: 06-30-2009, 08:46 PM

Tags for this Thread