分类: C/C++
2008-08-05 13:56:03
HWND g_hWnd = NULL; //处理消息的窗口句柄 unsigned long g_ulAddr = INADDR_NONE; //扫描的主机地址 DWORD g_dwTimeOut = 1000; //连接超时时间,以ms计 bool g_bTerminate = false; //是否用户发出结束扫描的标志 short g_nMaxThread = 200; //最大允许的扫描线程数,经试验不宜大于200 short g_nThreadCount = 0; //当前正在扫描的进程数2、StartScan 线程:
DWORD WINAPI StartScan(LPVOID lpParam) { tag_PORTS* pScanParam = (tag_PORTS*)lpParam; DWORD dwThreadId; unsigned short i; if (pScanParam->bSepecifiedPort) { for(i=0; i<=pScanParam->nCount; i ) { if (g_bTerminate) { break; //用户已发出结束扫描命令 } while(g_nThreadCount >= g_nMaxThread) { Sleep(10); } if (CreateThread(NULL, 0, DoScanPort, (LPVOID)new short(pScanParam->nArrOfPorts[i]), 0, &dwThreadId) != NULL) { g_nThreadCount ; } } } else { for(i=pScanParam->iStartPort; i<=pScanParam->iEndPort; i ) { if (g_bTerminate) { break; //用户已发出结束扫描命令 } while(g_nThreadCount >= g_nMaxThread) { Sleep(10); } if (CreateThread(NULL, 0, DoScanPort, (LPVOID)new short(i), 0, &dwThreadId) != NULL) { g_nThreadCount ; } } } //等待各端口扫描线程结束 while (g_nThreadCount > 0) { Sleep(50); } ::SendMessage(g_hWnd, SCAN_THREAD, STARTSCAN_COMPLETE, 0); delete pScanParam; return ERROR_SUCCESS; }3、DoScanPort 线程:
DWORD WINAPI DoScanPort(LPVOID lpParam) { DWORD dwRet; short nPort = *(short*) lpParam; delete lpParam; SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == INVALID_SOCKET) { AfxMessageBox("创建套接字失败!"); dwRet = ERROR_CREATE_SOCKET; } else { unsigned long flag = 1; if ((ioctlsocket(sock, FIONBIO, &flag) != 0)) { AfxMessageBox("未能改为非阻塞模式!"); dwRet = ERROR_MODIFY_FIONBIO; } else { sockaddr_in severAddr; severAddr.sin_family = AF_INET; severAddr.sin_port = htons(nPort); severAddr.sin_addr.S_un.S_addr = g_ulAddr; connect(sock, (sockaddr*)&severAddr, sizeof(severAddr)); struct fd_set mask; FD_ZERO(&mask); FD_SET(sock, &mask); struct timeval timeout; timeout.tv_sec = g_dwTimeOut / 1000; timeout.tv_usec = g_dwTimeOut % 1000; switch(select(0, NULL, &mask, NULL, &timeout)) { case -1: dwRet = ERROR_SELECT; break; case 0: dwRet = ERROR_SELECT_TIMEOUT; break; default: dwRet = ERROR_SUCCESS; }; } closesocket(sock); } g_nThreadCount --; if (dwRet == ERROR_SUCCESS) { ::SendMessage(g_hWnd, SCAN_THREAD, DOSCAN_FIND_PORT, nPort); } else { ::SendMessage(g_hWnd, SCAN_THREAD, DOSCAN_END_PORT, nPort); } return dwRet; }三、运行结果