Guest User

Untitled

a guest
Oct 23rd, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.51 KB | None | 0 0
  1. #include "stdafx.h"
  2.  
  3. #include <Windows.h>
  4. #include <Setupapi.h>
  5. #include <winusb.h>
  6.  
  7. #undef LowSpeed
  8. #include <Usbioctl.h>
  9.  
  10. #include <stdlib.h>
  11. #include <Devpkey.h>
  12. #include <iostream>
  13. #include <string>
  14. #include <memory>
  15. #include <strsafe.h>
  16.  
  17. #pragma comment(lib,"Setupapi.lib")
  18.  
  19.  
  20. void ErrorMes(LPTSTR lpszFunction)
  21. {
  22. // Retrieve the system error message for the last-error code
  23.  
  24. LPVOID lpMsgBuf;
  25. LPVOID lpDisplayBuf;
  26. DWORD dw = GetLastError();
  27.  
  28. FormatMessage(
  29. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30. FORMAT_MESSAGE_FROM_SYSTEM |
  31. FORMAT_MESSAGE_IGNORE_INSERTS,
  32. NULL,
  33. dw,
  34. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  35. (LPTSTR) &lpMsgBuf,
  36. 0, NULL );
  37.  
  38. // Display the error message
  39.  
  40. lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
  41. (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
  42. wprintf(L"%s failed with error %d: %s",
  43. lpszFunction, dw, lpMsgBuf);
  44.  
  45. LocalFree(lpMsgBuf);
  46. LocalFree(lpDisplayBuf);
  47.  
  48. }
  49.  
  50. typedef struct {
  51. wchar_t name[1024];//friendly name
  52. wchar_t id[1024];//instance id
  53.  
  54. } USB_DEVICE_PARAMS;
  55.  
  56. /*Получение имени устройства с указанным InstanceID*/
  57. BOOL GetDevice(wchar_t* id,wchar_t* output)
  58. {
  59. unsigned index;
  60. HDEVINFO hDevInfo;
  61. SP_DEVINFO_DATA DeviceInfoData;
  62. TCHAR id_upper[1024]=L"";
  63. TCHAR buf[1024]=L"";
  64. TCHAR match[1024];
  65. DEVPROPTYPE dpt=0;
  66.  
  67.  
  68. for(int i=0;i<wcslen(id);i++){
  69. id_upper[i]=toupper(id[i]);//преобразование в заглавные буквы
  70. }
  71.  
  72.  
  73.  
  74. // List all connected devices
  75. hDevInfo = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES);
  76. for (index = 0; ; index++) {
  77. DeviceInfoData.cbSize = sizeof(DeviceInfoData);
  78. if (!SetupDiEnumDeviceInfo(hDevInfo, index, &DeviceInfoData)) {
  79. return FALSE; // no match
  80. }
  81.  
  82. BOOL res=SetupDiGetDeviceProperty(hDevInfo,&DeviceInfoData,
  83. &DEVPKEY_Device_InstanceId,&dpt,(PBYTE)buf,1000,NULL,0);
  84. if(res==FALSE)continue;
  85.  
  86.  
  87. if(wcscmp(buf,id_upper)==0){
  88. //устройство найдено
  89. res=SetupDiGetDeviceProperty(hDevInfo,&DeviceInfoData,
  90. &DEVPKEY_Device_FriendlyName,&dpt,(PBYTE)buf,1000,NULL,0);
  91.  
  92. wcscpy(output,buf);//возврат имени
  93.  
  94. return TRUE;
  95. }
  96.  
  97.  
  98. }
  99. return FALSE;//устройство не найдено
  100.  
  101. }
  102.  
  103. /*Получение USB Mass Storage Device по указанным VID и PID*/
  104. BOOL GetMassStorageDevice(int vid,int pid,USB_DEVICE_PARAMS* output)
  105. {
  106. unsigned index;
  107. HDEVINFO hDevInfo;
  108. SP_DEVINFO_DATA DeviceInfoData;
  109. TCHAR HardwareID[1024];
  110. TCHAR buf[1024];
  111.  
  112. TCHAR match[1024];
  113. DEVPROPTYPE dpt=0;
  114. BOOL res;
  115.  
  116. //формируем строку для поиска
  117. StringCchPrintf(match,1024,L"VID_%04X&PID_%04X",vid,pid);
  118.  
  119.  
  120. // List all connected USB devices
  121. hDevInfo = SetupDiGetClassDevs(NULL, TEXT("USB"), NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES);
  122. for (index = 0; ; index++) {
  123. DeviceInfoData.cbSize = sizeof(DeviceInfoData);
  124. if (!SetupDiEnumDeviceInfo(hDevInfo, index, &DeviceInfoData)) {
  125. return FALSE; // no match
  126. }
  127.  
  128. res=SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_HARDWAREID, NULL,
  129. (BYTE*)HardwareID, sizeof(HardwareID), NULL);
  130. if(res==FALSE)continue;
  131.  
  132. if (_tcsstr(HardwareID, match)) {//найдено устройство, проверяем его тип
  133. res=SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_SERVICE, NULL,
  134. (BYTE*)buf, sizeof(buf), NULL);
  135. if(res==FALSE)continue;
  136.  
  137. if(wcscmp(buf,L"USBSTOR")==0){//устройство является Mass Storage
  138. res=SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC, NULL,
  139. (BYTE*)buf, sizeof(buf), NULL);
  140. if(res==FALSE)continue;
  141.  
  142. //получаем дочернее устройство
  143. res=SetupDiGetDeviceProperty(hDevInfo,&DeviceInfoData,
  144. &DEVPKEY_Device_Children,&dpt,(PBYTE)buf,1000,NULL,0);
  145. if(res==FALSE)continue;//нет дочерних устройств
  146.  
  147. wcscpy(output->id,buf);//возврат ID
  148.  
  149. GetDevice(buf,output->name);//возврат имени устройства
  150.  
  151. return TRUE; // найдено
  152. }
  153. }
  154. }
  155. return FALSE;//не найдено
  156.  
  157. }
  158.  
  159.  
  160.  
  161. int main()
  162. {
  163. setlocale(LC_ALL,"Russian");
  164.  
  165. GUID guid;
  166. /*USB HUB Interface class GUID*/
  167. HRESULT hr = CLSIDFromString(L"{F18A0E88-C30C-11D0-8815-00A0C906BED8}", (LPCLSID)&guid);
  168.  
  169. HDEVINFO deviceInfoHandle = SetupDiGetClassDevs(&guid, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  170.  
  171. if (deviceInfoHandle != INVALID_HANDLE_VALUE)
  172. {
  173. int deviceIndex = 0;
  174. while (true)
  175. {
  176. SP_DEVICE_INTERFACE_DATA deviceInterface = { 0 };
  177. deviceInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  178.  
  179. //получение всех USB-концентраторов
  180. if (SetupDiEnumDeviceInterfaces(deviceInfoHandle, 0, &guid, deviceIndex, &deviceInterface))
  181. {
  182. DWORD cbRequired = 0;
  183.  
  184. SetupDiGetDeviceInterfaceDetail(deviceInfoHandle, &deviceInterface, 0, 0, &cbRequired, 0);
  185. if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
  186. {
  187. PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetail =
  188. (PSP_DEVICE_INTERFACE_DETAIL_DATA)(new char[cbRequired]);
  189. memset(deviceInterfaceDetail, 0, cbRequired);
  190. deviceInterfaceDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
  191.  
  192. if (!SetupDiGetDeviceInterfaceDetail(deviceInfoHandle, &deviceInterface,
  193. deviceInterfaceDetail, cbRequired, &cbRequired, 0))
  194. {
  195. deviceIndex++;
  196. continue;
  197. }
  198.  
  199. // Initialize the structure before using it.
  200. memset(deviceInterfaceDetail, 0, cbRequired);
  201. deviceInterfaceDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
  202.  
  203. // Call the API a second time to retrieve the actual
  204. // device path string.
  205. BOOL status = SetupDiGetDeviceInterfaceDetail(
  206. deviceInfoHandle, // Handle to device information set
  207. &deviceInterface, // Pointer to current node in devinfo set
  208. deviceInterfaceDetail, // Pointer to buffer to receive device path
  209. cbRequired, // Length of user-allocated buffer
  210. &cbRequired, // Pointer to arg to receive required buffer length
  211. NULL); // Not interested in additional data
  212.  
  213. BOOL res;
  214.  
  215. /*Открываем устройство для отправки IOCTL*/
  216. HANDLE handle = CreateFile(deviceInterfaceDetail->DevicePath, GENERIC_WRITE, FILE_SHARE_WRITE,
  217. 0, OPEN_EXISTING, 0, 0);
  218.  
  219. if(handle!=INVALID_HANDLE_VALUE) {
  220.  
  221. //получаем число портов на концентраторе
  222. DWORD bytes_read=0;
  223. USB_HUB_INFORMATION_EX hubinfo;
  224.  
  225. res=DeviceIoControl(handle,IOCTL_USB_GET_HUB_INFORMATION_EX ,
  226. &hubinfo,sizeof(hubinfo),&hubinfo,sizeof(hubinfo),&bytes_read,0);
  227. if(res==FALSE)ErrorMes(L"DeviceIoControl");
  228.  
  229. USB_NODE_CONNECTION_INFORMATION_EX coninfo={0};//get conn info
  230. USB_NODE_CONNECTION_INFORMATION_EX_V2 con2={0};
  231.  
  232. for(int j=1;j<=(int)hubinfo.HighestPortNumber;j++){
  233.  
  234. coninfo.ConnectionIndex=j;
  235.  
  236. //получаем инфу о порте
  237. res=DeviceIoControl(handle,IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX ,
  238. &coninfo,sizeof(coninfo),&coninfo,sizeof(coninfo),&bytes_read,0);
  239.  
  240. if(res==FALSE){ErrorMes(L"DeviceIoControl");continue;}
  241.  
  242. if(coninfo.ConnectionStatus==0)continue;
  243.  
  244. USB_DEVICE_PARAMS usbdev={0};
  245.  
  246. //если на порте запоминающее устройство, вывести его данные
  247.  
  248. if(GetMassStorageDevice(coninfo.DeviceDescriptor.idVendor,
  249. coninfo.DeviceDescriptor.idProduct,&usbdev)!=FALSE)
  250. {
  251. printf("n- Hub %2d, Port %2d: USB v%x devicen",deviceIndex,
  252. j,(int)coninfo.DeviceDescriptor.bcdUSB);
  253. printf("VID_%04X PID_%04Xn",(int)coninfo.DeviceDescriptor.idVendor
  254. ,(int)coninfo.DeviceDescriptor.idProduct);
  255. wprintf(L"Device ID: %sn",usbdev.id);
  256. wprintf(L"Device name: %sn",usbdev.name);
  257. printf("Speed: %d",(int)coninfo.Speed);
  258.  
  259. switch((int)coninfo.Speed){
  260. case UsbLowSpeed:printf(" (low)n");break;
  261. case UsbFullSpeed:printf(" (full)n");break;
  262. case UsbHighSpeed:printf(" (high)n");break;
  263. case UsbSuperSpeed:printf(" (super)n");break;
  264. default:printf("n");break;
  265. }
  266.  
  267. //получение поддерживаемых протоколов
  268. con2.ConnectionIndex=j;
  269. con2.Length=sizeof(USB_NODE_CONNECTION_INFORMATION_EX_V2 );
  270. con2.SupportedUsbProtocols.Usb300=1;
  271.  
  272. res=DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2 ,
  273. &con2,sizeof(con2),&con2,sizeof(con2),&bytes_read,0);
  274. if(res==FALSE){ErrorMes(L"DeviceIoControl");continue;}
  275.  
  276. printf("Supported protocols: ");
  277. if(con2.SupportedUsbProtocols.Usb110)printf("USB 1.1; ");
  278. if(con2.SupportedUsbProtocols.Usb200)printf("USB 2.0; ");
  279. if(con2.SupportedUsbProtocols.Usb300)printf("USB 3.0; ");
  280. printf("n");
  281. }
  282.  
  283.  
  284. }//end for
  285.  
  286. CloseHandle(handle);
  287. }else{
  288. ErrorMes(L"CreateFile");//failed to open device
  289. }//endif
  290.  
  291.  
  292. delete[] deviceInterfaceDetail;
  293. }
  294. }
  295. else
  296. {
  297. break;
  298. }
  299.  
  300. ++deviceIndex;
  301. }
  302.  
  303. SetupDiDestroyDeviceInfoList(deviceInfoHandle);
  304. }
  305.  
  306. system("PAUSE");
  307. return 0;
  308. }
Add Comment
Please, Sign In to add comment