用asio写端口扫描器?缪缪数行而已

用asio写网络,简直是种享受啊,贴出来交流交流,代码直接拷到新工程的main.cpp里编译就行了

#include 
#include 

#include 
using namespace boost::asio;

#include 
using boost::system::error_code;

#include 
using boost::bind;

#include 
using std::cout;
using std::endl;

#include 
using std::strcmp;

#include 
using std::atoi;


typedef boost::shared_ptr socket_sp;
void conn_handler(socket_sp sock, ip::tcp::endpoint ep, const error_code& ec)
{
    if (!ec)
    {
        cout << ep.address().to_string() << ":" << ep.port() << endl;
    }

    if (ec != error::operation_aborted)
    {
        sock->close();
    }
}

void scan_ip(const char* start, const char* end, unsigned short port)
{
    unsigned long s = ntohl(inet_addr(start));
    unsigned long e = ntohl(inet_addr(end));
    if (s == -1 || e == -1)
    {
        return;
    }

    io_service io_service;
    boost::thread_group tg;

    do 
    {
        io_service::work work(io_service);
        tg.create_thread(bind(&io_service::run, &io_service));

        for (unsigned long i = s; i <= e; ++i)
        {
            socket_sp sock(new socket_sp::value_type(io_service));
            ip::tcp::endpoint ep(ip::address_v4(i), port);
            sock->async_connect(ep, bind(&conn_handler, sock, ep, placeholders::error));

            if (i == e) break;
        }
    } while (false);

    tg.join_all();
}

void scan_port(const char* ip, unsigned short start, unsigned short end)
{
    unsigned long ip_raw = ntohl(inet_addr(ip));
    if (ip_raw == -1)
    {
        return;
    }

    io_service io_service;
    boost::thread_group tg;

    do 
    {
        io_service::work work(io_service);
        tg.create_thread(bind(&io_service::run, &io_service));

        for (unsigned short i = start; i <= end; ++i)
        {
            socket_sp sock(new socket_sp::value_type(io_service));
            ip::tcp::endpoint ep(ip::address_v4(ip_raw), i);
            sock->async_connect(ep, bind(&conn_handler, sock, ep, placeholders::error));

            if (i == end) break;
        }
    } while (false);

    tg.join_all();
}

int main(int argc, char* argv[])
{
    if (argc == 5)
    {
        const char* cmd = argv[1];

        if (0 == strcmp(cmd, "--ip"))
        {
            scan_ip(argv[2], argv[3], atoi(argv[4]));            
        }
        else if (0 == strcmp(cmd, "--port"))
        {
            scan_port(argv[2], atoi(argv[3]), atoi(argv[4]));
        }
    }
    else
    {
        cout 
            << "brought to you by Hater.H ([email protected])" << endl
            << "usage:" << endl
            << "scanbot --ip   " << endl
            << "scanbot --port   " << endl;
    }

    return 0;
}



你可能感兴趣的:(用asio写端口扫描器?缪缪数行而已)