#pragma comment(lib,"ws2_32.lib")
#include <stdio.h>
#include <winsock2.h>
#define MAXTHREAD 500
#define PORTSTART 1
#define PORTEND 60000
#define TIMEOUT 1
#define WAITTIME 10
#define IP "61.135.169.105" //百度地址
FILE * logHandle;
DWORD PortScan(LPVOID lp);
typedef struct
{
SOCKET s;
sockaddr_in addr;
} mySocket;//传递参数
int threadCount = 0;
CRITICAL_SECTION c;
int main()
{
WSADATA ws;
InitializeCriticalSection(&c);
fopen_s(&logHandle,"C:\\Documents and Settings\\Administrator\\桌面\\log.txt","w+");
int nRet = WSAStartup(MAKEWORD(2,2),&ws);
if(nRet !=0)
{
fprintf(logHandle,"Failed to initial the socketdll,%ld\n",WSAGetLastError());
return 1;
}
for(int i=PORTSTART;i<=PORTEND;i++)
{
mySocket *listenSocket = new mySocket;
listenSocket->s = socket(AF_INET,SOCK_STREAM,0);
if(listenSocket->s == INVALID_SOCKET)
{
fprintf(logHandle,"create socket error with %ld\n",WSAGetLastError());
return 1;
}
listenSocket->addr.sin_addr.s_addr = inet_addr(IP);
listenSocket->addr.sin_family = AF_INET;
memset(listenSocket->addr.sin_zero,0,8);
listenSocket->addr.sin_port = htons(i); //创建监听的socket
while(threadCount >MAXTHREAD)
{
Sleep(5000);
}
if(CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)PortScan,(LPVOID)listenSocket,NULL,NULL))
{
threadCount ++;
}
}
while(threadCount >0)
{
Sleep(5000);
}
WSACleanup();
return 0;
}
DWORD PortScan(LPVOID lp)
{
int nRet;
mySocket *s = (mySocket *)lp;
//EnterCriticalSection(&c);
int port = ntohs(s->addr.sin_port);
connect(s->s,(sockaddr *)&s->addr,sizeof(sockaddr_in));
unsigned long flag = 1;
nRet = ioctlsocket(s->s,FIONBIO,&flag);
if(nRet != 0)
{
fprintf(logHandle,"ioc error with %ld\n",WSAGetLastError());
}
fd_set mask;
FD_ZERO(&mask);
FD_SET(s->s,&mask);
struct timeval tm = {1,0};
switch(select(0,NULL,&mask,NULL,&tm))
{
case -1:
fprintf(logHandle,"%d port connect error %ld\n",port,WSAGetLastError());
break;
case 0:
fprintf(logHandle,"%d port time out\n",port);
break;
default:
fprintf(logHandle,"%d port open\n",port);
}
closesocket(s->s);
threadCount --;
delete s;
//LeaveCriticalSection(&c);
return 0;
}
转载于:https://www.cnblogs.com/S-volcano/archive/2012/09/04/2670731.html