我想在C++中做一個端口掃描器,這樣我就可以從我的網絡中某些端口打開的某些設備獲取IP地址。我實現了一個超時,因爲當我測試網絡中的每個IP地址時,如果我沒有收到響應,它會自動關閉連接。C++端口掃描器
如果我把這個超時大約30秒的時間,它只是檢測所有設備關閉,如果我把一個更大的值它掛起,永遠不會結束。
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
using namespace std;
static bool port_is_open(string ip, int port){
struct sockaddr_in address; /* the libc network address data structure */
short int sock = -1; /* file descriptor for the network socket */
fd_set fdset;
struct timeval tv;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(ip.c_str()); /* assign the address */
address.sin_port = htons(port);
/* translate int2port num */
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
connect(sock, (struct sockaddr *)&address, sizeof(address));
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 0; /* timeout */
tv.tv_usec = 50;
if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0){
close(sock);
return true;
}else{
close(sock);
return false;
}
}
return false;
}
int main(int argc, char **argv){
int i=1;
int port = 22;
while (i<255) {
string ip = "10.0.60.";
std::string host = std::to_string(i);
ip.append(host);
if (port_is_open(ip, port)){
printf("%s:%d is open\n", ip.c_str(), port);
}
i++;
}
return 0;
}
30次使用? 30微秒超時? –
你的問題是什麼? –
'tv.tv_usec = 50'等於50 usec – nrathaus