Skip to content

Instantly share code, notes, and snippets.

@tbielawa
Last active March 14, 2016 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbielawa/d49b6e7a057377f6a0ee to your computer and use it in GitHub Desktop.
Save tbielawa/d49b6e7a057377f6a0ee to your computer and use it in GitHub Desktop.
Reading block device sizes in python - More in the blog post: https://blog.lnx.cx/?p=678
$ gcc ./linux-request-code.c
$ ./a.out
Block count request code: 0x80081272
#include <linux/fs.h>
#include<stdio.h>
int main()
{
printf("Block count request code: 0x%lx\n", BLKGETSIZE64);
}
#include <sys/disk.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>
/* Originally posted in http://stackoverflow.com/questions/9073614/open-raw-disk-and-get-size-os-x/9764508#9764508 */
int main()
{
// Open disk
uint32_t dev = open("/dev/disk1",O_RDONLY);
if (!dev || dev == -1)
return 1;
uint64_t sectors = 0;
// Query the number of sectors on the disk
ioctl(dev, DKIOCGETBLOCKCOUNT, &sectors);
uint32_t sectorSize = 0;
// Query the size of each sector
ioctl(dev, DKIOCGETBLOCKSIZE, &sectorSize);
uint64_t diskSize = sectors * sectorSize;
printf("Disk dize: %llu", diskSize);
return 0;
}
$ gcc ./osx-request-code.c
$ ./a.out
Block size request code: 0x40046418
Block count request code: 0x40086419
#include <sys/disk.h>
#include<stdio.h>
int main()
{
printf("Block size request code: 0x%lx\n", DKIOCGETBLOCKSIZE);
printf("Block count request code: 0x%lx\n", DKIOCGETBLOCKCOUNT);
}
import fcntl
import struct
device_path = '/dev/sda'
req = 0x80081272 # BLKGETSIZE64, result is bytes as unsigned 64-bit integer (uint64)
buf = ' ' * 8
fmt = 'L'
with open(device_path) as dev:
buf = fcntl.ioctl(dev.fileno(), req, buf)
bytes = struct.unpack(fmt, buf)[0]
print device_path, 'is about', bytes / (1024 ** 2), 'megabytes'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment