Boost ASIO return Bad file descriptor

Viewed 149

I try to use asio icmp services, but i get an error: "Bad file descriptor ", i use ubuntu20.04 and boost1.74.0. I want to test icmp service, i write a test use ASIO, and i use tcpdump for ping request. The tcpdump command is shell

 sudo tcpdump -i any icmp -vv -XX

and my code is

#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include <chrono>
#include <string>

class pinger
{
public:
    pinger(boost::asio::io_context& io_context)
            : resolver_(io_context), socket_(io_context)
    {
        start_receive();
    }


private:

    void start_receive()
    {

        socket_.async_receive_from(boost::asio::buffer(receive,1024),destination,
                                   [this](boost::system::error_code ec, std::size_t size){

                                       if (ec)
                                           std::cout<<ec.message()<<std::endl;
                                       if (size>0)
                                           std::cout<<size<<std::endl;
                                   });
    }

    boost::asio::ip::icmp::resolver resolver_;
    boost::asio::ip::icmp::socket socket_;
    unsigned char receive[1024];
    boost::asio::ip::icmp::endpoint destination;
};


int main() {


    try {

        boost::asio::io_context io_context;
        pinger service = pinger(io_context);
        io_context.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;

}

It seems socket_.async_receive_from error directly rather than wait for receive data. I'm a new c++ learner, and first ues boost.asio. thank you very much.

1 Answers
Related