Windows多线程端口扫描
还不是很了解多线程,先简单运用下。
1 /* 2 2015.5 HT 3 多线程端口扫描 4 5 netstat -an 6 7 */ 8 9 #include <iostream> 10 #include <process.h> 11 #include <winsock2.h> 12 #pragma comment(lib,"ws2_32.lib") 13 using namespace std; 14 15 // 线程传递的端口参数 16 typedef struct 17 { 18 unsigned int min_port; 19 unsigned int max_port; 20 }Port; 21 Port *lpPort = new Port; 22 // 线程数 23 int Thread_NUM; 24 // 互斥量 25 HANDLE hMutex; 26 27 DWORD WINAPI scan(LPVOID lpParameter) 28 { 29 // 获得参数 30 Port* port = (Port*)lpParameter; 31 SOCKET sockfd = NULL; 32 SOCKADDR_IN sin; 33 sin.sin_family = AF_INET; 34 sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); 35 36 for (unsigned int i = port->min_port; i <= port->max_port; ++i) 37 { 38 if (sockfd == NULL) 39 { 40 // 创建套接字 41 sockfd = socket(AF_INET, SOCK_STREAM, 0); 42 if (sockfd == INVALID_SOCKET) 43 { 44 cout << "创建socket失败!" << endl; 45 return 0; 46 } 47 } 48 sin.sin_port = htons(i); 49 // 连接服务器 50 int ret = connect(sockfd, (sockaddr *)&sin, sizeof(sockaddr)); 51 // 请求一个互斥量的访问权 52 WaitForSingleObject(hMutex, INFINITE); 53 if (ret == SOCKET_ERROR) 54 { 55 cout << "Port: " << i << " not open !" << endl; 56 } 57 else 58 { 59 cout << "Port: " << i << " open !" << endl; 60 closesocket(sockfd); 61 sockfd = NULL; 62 } 63 // 释放一个互斥量的访问权 64 ReleaseMutex(hMutex); 65 } 66 67 return 0; 68 } 69 70 int main() 71 { 72 WSADATA wsaData; 73 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) 74 { 75 cout << "找不到 WinSock dll!" << endl; 76 return 0; 77 } 78 79 hMutex = CreateMutex(NULL, FALSE, NULL); 80 81 cout << "输入起始端口,结束端口号: " ; 82 cin >> lpPort->min_port >> lpPort->max_port; 83 cout << "输入线程数(小于200): "; 84 cin >> Thread_NUM; 85 HANDLE handle[200]; 86 int Scan_Len = (lpPort->max_port - lpPort->min_port) / Thread_NUM; 87 88 for (int i = 0; i < Thread_NUM; ++i) 89 { 90 Port *NewPort = new Port; 91 NewPort->min_port = lpPort->min_port + Scan_Len * i; 92 if (i < (Thread_NUM - 1)) 93 NewPort->max_port = NewPort->min_port + Scan_Len - 1; 94 else 95 { 96 NewPort->max_port = lpPort->max_port; 97 handle[i] = (HANDLE)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)scan, NewPort, 0, NULL); 98 break; 99 } 100 handle[i] = (HANDLE)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)scan, NewPort, 0, NULL); 101 } 102 WaitForMultipleObjects(Thread_NUM, handle, TRUE, INFINITE); 103 104 CloseHandle(hMutex); 105 return 0; 106 }