Skip to content

Instantly share code, notes, and snippets.

Last active September 23, 2023 12:08
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Determining block device's sector size in Linux+Python
import fcntl
import os
import struct
import array
import sys
def ioctl_read_uint32(fd, req):
buf = array.array('c', [chr(0)] * 4)
fcntl.ioctl(fd, req, buf)
return struct.unpack('I',buf)[0]
def ioctl_read_uint64(fd, req):
buf = array.array('c', [chr(0)] * 8)
fcntl.ioctl(fd, req, buf)
return struct.unpack('L',buf)[0]
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage: %s block_device" % sys.argv[0]
device = sys.argv[1]
fd =, os.O_RDONLY)
logical_sector_size = ioctl_read_uint32(fd, BLKSSZGET)
physical_sector_size = ioctl_read_uint32(fd, BLKPBSZGET)
device_size = ioctl_read_uint64(fd, BLKGETSIZE64)
except IOError as e: # Some platform doesn't support BLKGETSIZE64
if e.errno == 25: # "Inappropreate ioctl for device"
device_size = ioctl_read_uint32(fd, BLKGETSIZE) * logical_sector_size
else: raise
print "Block device: %s" % device
print " Entire device capacity: %d" % device_size
print " Logical sector size: %d" % logical_sector_size
print " Physical sector size: %d" % physical_sector_size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment