简单的端口扫描程序源代码作者:miyagi#includewinsock2.h#includewindows.h#includestdio.h#pragmacomment(lib,ws2_32.lib)//defineglobalvariablelongMaxThread=100;HANDLEhSemaphore;longPreviousCount=0;intTargetIP;DWORDWINAPIportscan(LPVOIDlp);intmain(intargc,char**argv){HANDLEhThread=NULL;WSADATAwsd;inti;DWORDdwThreadID;if(argc!=4){printf(\n%s,scanportbymiyagi\nusage:%stargetIPStartPortStopPort\n,argv[0],argv[0]);return1;}__try{//loadwinsocklibraryif(WSAStartup(MAKEWORD(2,2),&wsd)!=0){printf(Failedtoloadwinsocklibrary!Error%d\n,GetLastError());__leave;}//createsemaphorehSemaphore=CreateSemaphore(NULL,MaxThread,MaxThread,NULL);if(hSemaphore==NULL){printf(Failedtocreatesemaphore!Error%d\n,GetLastError());__leave;}//gettargetIPandtargetportrangeTargetIP=inet_addr(argv[1]);intTargetHost=ntohl(TargetIP);intStartPort=atoi(argv[2]);intStopPort=atoi(argv[3]);//createthreadtoscanfor(i=StartPort;i=StopPort;i++){hThread=CreateThread(NULL,0,portscan,(LPVOID)i,0,&dwThreadID);if(hThread==NULL){printf(Failetocreatethread!Error%d\n,GetLastError());break;}Sleep(10);CloseHandle(hThread);WaitForSingleObject(hSemaphore,INFINITE);}//waitforallthreaddonewhile(1){WaitForSingleObject(hSemaphore,INFINITE);if(!ReleaseSemaphore(hSemaphore,1,&PreviousCount)){printf(\nmain()ReleaseSemaphorefailed:%d,GetLastError());Sleep(5000);break;}if(PreviousCount=(MaxThread-1)){printf(\n^o^scanend!\n);break;}Sleep(500);}}//tryend__finally{CloseHandle(hSemaphore);WSACleanup();}return0;}DWORDWINAPIportscan(LPVOIDlp){structsockaddr_inserver;SOCKETs=INVALID_SOCKET;intiPort=(int)lp;s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(s==INVALID_SOCKET){printf(Failetocreatesocket!Error%d,GetLastError());ExitProcess(1);}server.sin_family=AF_INET;server.sin_addr.S_un.S_addr=TargetIP;server.sin_port=htons(iPort);__try{//connecttotargetif(connect(s,(structsockaddr*)&server,sizeof(server))!=0)__leave;elseprintf(portTCP%disopen!\n,ntohs(server.sin_port));}//tryend__finally{Sleep(500);if(!ReleaseSemaphore(hSemaphore,1,NULL))printf(\nThreadReleaseSemaphoreFailed:%d,GetLastError());closesocket(s);}return0;