如何编写最简单的端口扫描程序

早于2002年

一:新建一个支持MFC的WIN32控制台应用程序;
二:在 SCANPORT.CPP文件中,添加两个全局变量:

       int i ;
       CSocket sockClient;
       

       再添加线程处理函数定义:
     
          DWORD WINAPI ScanPorts(LPVOID);

 
    int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])


代码如下:

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 int nRetCode = 0;
 
 // initialize MFC and print and error on failure
 if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
 {
  // TODO: change error code to suit your needs
  cerr << _T("Fatal Error: MFC initialization failed") << endl;
  nRetCode = 1;
 }
 else
 {
  ::SetConsoleTitle("Scan ports -- Written by CodeWorrior");


/////////////////////////////////////
//
// 扫描的主机,可以改为用户输入
//
//////////////////////////////////////
  // TODO: code your application's behavior here.
  AfxSocketInit(NULL);

  for(i=1;i<=10;i++)
  {
   HANDLE hThread;
   DWORD dwThreadID;
     file://cout<<i<<endl;
   hThread = CreateThread(NULL,0,ScanPorts,(LPVOID)i,0,&dwThreadID);
   Sleep(1000);
   ::WaitForSingleObject(hThread,200);
   CloseHandle(hThread);
  }
  
 }
 cout<<endl;
 return nRetCode;
}


DWORD WINAPI ScanPorts(LPVOID p)
{ 
 try
 { 
  int j = (i-1)*100;
  printf("Thread %d starting\n",i);
  for(j;j<i*100;j++)
  {
  
   sockClient.Create();
   
   if(sockClient.Connect("10.128.0.3",1028))
   {
    cout<<endl;
    cout<<"port"<<"  "<<j<<"   ";
    cout<<"Connect to server succeed!"<<endl;;
    sockClient.Close();
   }
   else
   {
     printf("port %d connect to server failed\n",j);      //可以显示正在连接那个端口
     sockClient.Close();
   }
  }
 }
 catch(...)
 {
  sockClient.Close();
 }
 printf("Thread %d Terminate!\n",i);
 return 0;
}
posted @ 2011-05-10 16:52  自由行走  阅读(525)  评论(0编辑  收藏  举报