简单的端口扫描程序源代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
简单的端口扫描程序源代码
作者:miyagi
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
//define global variable
long MaxThread=100;
HANDLE hSemaphore;
long PreviousCount=0;
int TargetIP;
DWORD WINAPI portscan(LPVOID lp);
int main(int argc, char **argv)
{
HANDLE hThread=NULL;
WSADATA wsd;
int i;
DWORD dwThreadID;
if(argc!=4)
{
printf("\n%s,scan port by miyagi\n"
"usage:%s
}
__try
{
//load winsock library
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
printf("Failed to load winsock library!Error %d\n",GetLastError());
__leave;
}
//create semaphore
hSemaphore=CreateSemaphore(NULL,MaxThread,MaxThread,NULL);
{
printf("Failed to create semaphore!Error %d\n",GetLastError());
__leave;
}
//get target IP and target port range
TargetIP=inet_addr(argv[1]);
int TargetHost=ntohl(TargetIP);
int StartPort=atoi(argv[2]);
int StopPort=atoi(argv[3]);
//create thread to scan
for(i=StartPort;i<=StopPort;i++)
{
hThread=CreateThread(NULL, 0, portscan, (LPVOID)i , 0, &dwThreadID); if(hThread==NULL)
{
printf("Faile to create thread!Error %d\n",GetLastError());
break;
}
Sleep(10);
CloseHandle(hThread);
WaitForSingleObject(hSemaphore, INFINITE);
}
//wait for all thread done
while(1)
{
WaitForSingleObject(hSemaphore, INFINITE);
if(!ReleaseSemaphore(hSemaphore, 1, &PreviousCount))
{
printf("\nmain() ReleaseSemaphore failed:%d",GetLastError());
Sleep(5000);
break;
}if(PreviousCount=(MaxThread-1))
{
printf("\n^o^ scan end!\n");
break;
}
Sleep(500);
}
}//try end
__finally
{
WSACleanup();
}
return 0;
}
DWORD WINAPI portscan(LPVOID lp)
{
struct sockaddr_in server;
SOCKET s=INV ALID_SOCKET;
int iPort=(int)lp;
s=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(s==INV ALID_SOCKET)
{
printf("Faile to create socket!Error %d",GetLastError()); ExitProcess(1);
}
server.sin_family=AF_INET;
server.sin_addr.S_un.S_addr=TargetIP;
server.sin_port=htons(iPort);
__try
{
//connect to target
if(connect(s, (struct sockaddr *)&server, sizeof(server))!=0)
__leave;
else
printf(" port TCP %d is open!\n",ntohs(server.sin_port));
}//try end
__finally
{
Sleep(500);
if(!ReleaseSemaphore(hSemaphore,1, NULL))
printf("\nThread ReleaseSemaphore Failed:%d",GetLastError()); closesocket(s);
}
return 0;