c++ - 调用 IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER 时句柄无效

标签 c++ windows ioctl

有人有使用 c/c++ IOCTL 调用的经验吗? 基本上我试图确定 USB 内存棒插入哪个端口。 我有所有 USB 信息和音量信息。显然,要链接这两个信息 block ,我需要驱动程序 key 或序列号。 但是,当调用 DeviceIoControl 时,我得到无效句柄作为“最后一个错误代码”

我的U盘挂载到c:\中的一个目录(不是盘符)见下

//get a handle on the volume
HANDLE hVolume;
DWORD dwAccessFlags;

dwAccessFlags = GENERIC_READ | GENERIC_WRITE;  

hVolume = CreateFile(L"C:\_USB\MP1",
    dwAccessFlags,
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL,
    OPEN_EXISTING,
    0,
    NULL );
if (hVolume == INVALID_HANDLE_VALUE) {
    printf("Invalid Handle");
}

//use the handle
MEDIA_SERIAL_NUMBER_DATA* pserialNumberData = new MEDIA_SERIAL_NUMBER_DATA;
wstring result;
//HANDLE hVolume = OpenVolume(vname.substr(0, vname.length() - 1).c_str());
DWORD   bytesReturned = 0;
LPDWORD lpBytesReturned = &bytesReturned;

OVERLAPPED over;
LPOVERLAPPED lpOver = &over;
BOOL success = 1;
success = DeviceIoControl(
    (HANDLE) hVolume,                      // handle to device
     IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER, // dwIoControlCode
     NULL,                                  // lpInBuffer
     0,                                     // nInBufferSize
    (LPVOID) pserialNumberData,                  // output buffer
    (DWORD) sizeof(MEDIA_SERIAL_NUMBER_DATA),                       // size of output buffer
    (LPDWORD) lpBytesReturned,             // number of bytes returned
    (LPOVERLAPPED) lpOver            // OVERLAPPED structure
    );
wcout << L"--> GetSn() DeviceIoControl success " << success << endl;
wcout << L"--> GetSn() DeviceIoControl Last error number " << GetLastError() << endl;
wcout << L"--> GetSn() DeviceIoControl Bytes Returned " << bytesReturned << endl;
wcout << L"--> GetSn() DeviceIoControl struct size " << sizeof(MEDIA_SERIAL_NUMBER_DATA) << endl;

最佳答案

如果您查看 DeviceIoControl 的备注部分功能,它说:

To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the driver associated with a device. To specify a device name, use the following format:
\\.\DeviceName

DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to open handles to the physical drives on a system.

您没有打开设备句柄,因此 DeviceIoControl 不适用于这种情况。

关于c++ - 调用 IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER 时句柄无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9808220/

相关文章:

c++ - 提升 : dereference a template argument if it's a pointer

python - 使用 cmake 安装 protobuf 时出现问题

c# - 如何从某个进程获取打开的套接字列表?

windows - Powershell 检索作业给出 "cannot index into null array error"

linux-kernel - `ioctl`读写GPIO : invalid argument

android - ioctl LOOP_SET_FD 失败

c - 在内核中访问用户空间结构的成员给出了错误的值

c++ - 重新审视 switch 内部的对象实例化 (c++)

c++ - 为什么 std::span 缺少 size_type?

c# - 可读性 a=b=c 或 a=c; b=c;?