所以我在windows上为C开发了一个端口扫描器,但我注意到在一些IP上它运行得非常慢。这是我的代码:
DWORD WINAPI connectPortW(LPVOID lpParam)
{
HANDLE hStdout;
PMYDATA pDataArray;
WSADATA firstsock;
SOCKET s;
struct sockaddr_in sa;
int err;
char * openPorts = (char *)malloc(sizeof(char)*256);
memset(&openPorts[0], 0, strlen(openPorts));
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if(hStdout == INVALID_HANDLE_VALUE )
{
return 1;
}
pDataArray = (PMYDATA)lpParam;
strncpy((char *)&sa,"",sizeof sa);
sa.sin_family = AF_INET;
if (WSAStartup(MAKEWORD(2,0),&firstsock) != 0)
{
fprintf(stderr,"WSAStartup() failed");
exit(1);
}
sa.sin_addr.s_addr = inet_addr(pDataArray->ip);
s = socket(AF_INET, SOCK_STREAM, 0); //make net a valid socket handle
if(s < 0)
{
perror("\nSocket creation failed"); // perror function prints an error message to stderr
exit(1);
}
sa.sin_port = htons(pDataArray->port);
err = connect(s, (struct sockaddr *)&sa, sizeof sa);
//connection not accepted
if(err == SOCKET_ERROR)
{
printf("%s %-5d Winsock Error Code : %d\n", pDataArray->ip, pDataArray->port, WSAGetLastError());
strcpy("NULL", openPorts);
fflush(stdout);
}
//connection accepted
else
{
printf("%s %-5d accepted \n", pDataArray->ip, pDataArray->port);
sprintf(openPorts, "%i,", pDataArray->port);
if(shutdown(s, SD_BOTH ) == SOCKET_ERROR )
{
perror("\nshutdown");
exit(1);
}
}
closesocket(s);
fflush(stdout);
strcpy(pDataArray->openPorts, openPorts);
free(openPorts);
return 0;
}
请记住,我已经使用了线程,并且每个线程都为同一 IP 上的不同端口(0 - 1024)调用此函数。
那么我怎样才能加快速度呢?我一直看到人们在谈论非阻塞,这会加快速度吗?如果可以,我该如何实现。谢谢!
编辑:在上述“慢”IP 之一上从 0 到 1024 扫描需要 614 秒(10 分钟)
编辑2:我开始尝试使用非阻塞......我这样做对吗?
ioctlsocket(s, FIONBIO, &on);
connect(s, (struct sockaddr *)&sa, sizeof sa);
FD_ZERO(&fds);
FD_SET(s, &fds);
err = select(s, &fds, &fds, &fds, &tv);
if (err != SOCKET_ERROR && err != 0)
{
sprintf(openPorts + strlen(openPorts),"%i,", pDataArray->port);
}
closesocket(s);
编辑 3:似乎这种新方法给了我不准确的结果,但速度要快得多。与在同一 IP 上运行 nmap 的结果相比,我似乎获得了更多的开放端口。