1. 程式人生 > >C++掃描指定主機開放的埠

C++掃描指定主機開放的埠

C++掃描指定主機開放的埠,OS提供了connect()系統呼叫,用於與遠端主機某埠建立連線,如果遠端主機該埠處於幀聽狀態,則connect()連線成功;否則說明該埠關閉。

// ScanPorts.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include<iostream> using namespacestd; #include<WinSock2.h> #pragma comment (lib,"ws2_32.lib") #define STATUS_FALIED 0xFFFF unsignedlongserverIP
; longMaxThread=200; longThreadCount=0; long*aa=&ThreadCount; //掃描埠的執行緒 DWORD WINAPI ScanPort(LPVOID lpParam){ shortPort=*(short*)lpParam; InterlockedIncrement(aa); //建立流式套接字 SOCKET sock=socket(AF_INET,SOCK_STREAM,0); if(sock==INVALID_SOCKET){ cout<<"建立套接字失敗!"<<endl; return0; }
else{ //填充伺服器地址 sockaddr_in severAddr; severAddr.sin_family=AF_INET; severAddr.sin_port=htons(Port); severAddr.sin_addr.S_un.S_addr=serverIP; //判斷此機器是否開啟 connect(sock,(sockaddr*)&severAddr,sizeof(severAddr)); structfd_set write; FD_ZERO(&write); FD_SET(sock,&write); //初始化超時時間 struct
timeval timeout; timeout.tv_sec=100/1000; timeout.tv_usec=0; if(select(0,NULL,&write,NULL,&timeout)>0) { cout<<Port<<","; }; closesocket(sock); } InterlockedDecrement(aa); return0; } voidmain(intargc,char*argv[]) { if(argc!=2){ cout<<"請輸入目的主機IP地址"<<endl; } //建立與socket庫的繫結 WSADATA WSAData; if(WSAStartup(MAKEWORD(2,2),&WSAData)!=0) { cout<<"WSAStartup falied!"<<GetLastError()<<endl; ExitProcess(STATUS_FALIED); } serverIP=inet_addr(argv[1]); cout<<"下列埠已開放:"<<endl; for(inti=1;i<1024;i++){ //超過最大允許執行緒數等待 while(ThreadCount>=MaxThread) Sleep(10); //建立執行緒,掃描埠 DWORD ThreadID; CreateThread(NULL,0,ScanPort,(LPVOID)newshort(i),0,&ThreadID); } //還有沒有結束的執行緒,等待 while(ThreadCount>0) Sleep(50); WSACleanup(); }