C++端口扫描程序

C++ Port Scanner

本文关键字:程序 扫描 C++      更新时间:2023-10-16

我正在尝试用c ++进行端口扫描,以便我可以从网络中打开了某个端口的某些设备获取IP地址。我实现了超时,因为当我测试网络中的每个 IP 地址时,如果我没有得到响应,它会自动关闭连接。

如果我把这个超时放在大约 30 u秒,它只会检测到所有关闭的设备,如果我放一个更大的值,它会挂起并且永远不会完成。

#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 openn", ip.c_str(), port);                
        }            
        i++;
    }           
    return 0;        
}

您可以将逻辑包装成异步调用,并以合理的超时并行启动(例如 10 秒,因为 30us 在标准条件下毫无意义)。线程将使程序加速大约 255 倍,在最坏的情况下,在此超时发生后,它将完成:

...
#include <iostream>
#include <thread>
#include <vector>
#include <sstream>
...
void task(std::string ip, int port){
    if (port_is_open(ip, port))
        cout << ip << ":" << port << " is openn";
}
int main(int argc, char **argv){        
    const std::string ip_prefix = "10.0.60.";
    const int port = 22;
    std::vector<std::thread *> tasks;
    for (int i=0; i<255; i++){      
        std::ostringstream ip;
        ip << ip_prefix << i;
        tasks.push_back(new std::thread(task, ip.str(), port));
    }
    for (int i=0; i<255; i++){
        tasks[i]->join();
        delete tasks[i];
    }
    return 0;
}

您可能希望像这样编译它:g++ -std=c++11g++ -std=c++0x -pthread(对于较旧的 GCC)。