星期一, 9月 12, 2011

Use C language to get Hard Disk Serial Number in Linux





/*
* It gets the hard disk information in this case serial no.
* It uses ioctl() system call
*/
#include <stdio.h>
#include <string.h>
#include <linux/types.h>
#include <linux/hdreg.h>
#include <linux/fcntl.h>

//
int hd_serial(char *searial_no);
void trim(char *s);
//
int main() {
char serial_no[256];

if (hd_serial(serial_no)){
printf("%s",serial_no);
}

return (0);
}
// ----------------------------------
int hd_serial(char *serial_no){
int fd,err,i;

/* structure to get disk information and
* returned by HDIO_GET_IDENTITY, as per ANSI ATA2 rev.2f spec
*/
struct hd_driveid hd;

/* open the device */
if( (fd=open("/dev/sda", O_RDONLY ) ) < 0 ){
//perror("Device Open Error");
return 0;
}

/* get required info */
if( (err = ioctl(fd, HDIO_GET_IDENTITY, &hd) ) < 0){
//perror("IOCTL err");
return 0;
}else{
//printf("Serial No = %s\n",hd.serial_no);
strcpy(serial_no, hd.serial_no);
trim(serial_no);
//printf("%s",serial_no);
}
return 1;
}
// ------------- trim ---------------------------
void trim(char *s){
int i=0, j, k, l=0;

while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
i++;

j = strlen(s)-1;
while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
j--;

if(i==0 && j==strlen(s)-1) { }
else if(i==0) s[j+1] = '\0';
else {
for(k=i; k<=j; k++) s[l++] = s[k];
s[l] = '\0';
}
}
//----------------------------------------------