我試圖使用以下代碼片段掃描我的ip上打開的端口,它需要超過20分鐘才能完成,但我需要在不到一分鐘內完成任務。如果有人能給我一個想法,我很欣賞。先謝謝了。掃描打開端口
- (void)scanForOpenPorts
{
struct hostent *host;
int err, i, sock;
char hostname[100] = "192.168.1.17";
struct sockaddr_in sa;
//Initialise the sockaddr_in structure
memcpy((char*)&sa , "" , sizeof sa);
sa.sin_family = AF_INET;
//direct ip address, use it
if(isdigit(hostname[0]))
{
printf("Doing inet_addr...");
sa.sin_addr.s_addr = inet_addr(hostname);
printf("Done\n");
}
//Resolve hostname to ip address
else if((host = gethostbyname(hostname)) != 0)
{
printf("Doing gethostbyname...");
memcpy((char*)&sa.sin_addr , (char*)host->h_addr , sizeof sa.sin_addr);
printf("Done\n");
}
else
{
herror(hostname);
exit(2);
}
//Start the port scan loop
printf("Starting the portscan loop : \n");
NSLog(@"Start Time: %@", [NSDate date]);
for(i = 0; i <= 65536; i++)
{
//Fill in the port number
sa.sin_port = htons(i);
//Create a socket of type internet
sock = socket(AF_INET , SOCK_STREAM , 0);
//Check whether socket created fine or not
if(sock < 0)
{
perror("\nSocket");
exit(1);
}
//Connect using that socket and sockaddr structure
err = connect(sock , (struct sockaddr*)&sa , sizeof sa);
//not connected
if(err < 0)
{
//printf("%s %-5d %s\r" , hostname , i, strerror(errno));
fflush(stdout);
}
//connected
else
{
printf("%-5d open\n", i);
}
close(sock);
}
NSLog(@"End Time: %@", [NSDate date]);
printf("\r");
fflush(stdout);
}
如果這是正在運行的代碼,則它在SO上是無關緊要的。這不是代碼審查網站。那不是C代碼!不要爲非C代碼添加C標籤。 – Olaf
你有C語法錯誤,像memcpy這樣的東西沒有意義;我沒有太多的信任,你甚至不明白你想要做什麼。我虛心地建議你在做這樣複雜的事情之前開始學習C語言。 –
@Olaf建議它*應該*爲C ... –