如何获取套接字的响应

How to get the response of the socket?

本文关键字:套接字 响应 获取 何获取      更新时间:2023-10-16

我在boost_asio的帮助下开发了简单的跟踪路由程序。我用这个例子。我很少更改此示例以实现traceroute而不是ping

pinger(boost::asio::io_service& io_service, const char* destination)
        : resolver_(io_service), socket_(io_service, icmp::v4()),
        timer_(io_service), sequence_number_(0), num_replies_(0)
{
    boost::asio::ip::unicast::hops option(%1%); // 1 is a param
    socket_.set_option(option);
    icmp::resolver::query query(icmp::v4(), destination, "");
    destination_ = *resolver_.resolve(query);
    start_send();
    start_receive();
}

我有一个问题。当time to live少于它需要时,我没有任何反应。我希望得到这样的东西:

C:Users>ping 91.92.100.254 -i 2
Pinging 91.92.100.254 with 32 bytes of data:
Reply from 10.110.50.251: TTL expired in transit.
Reply from 10.110.50.251: TTL expired in transit.
Reply from 10.110.50.251: TTL expired in transit.

我没有经常使用boost asio(或boost,就此而言),所以我不确定TTL过期错误会发送到哪个处理程序,但这应该让你走上正确的轨道......

在开始等待回复的位置,添加 _1 占位符以将套接字错误传递给 handle_receive 方法:

// Wait for a reply. We prepare the buffer to receive up to 64KB.
// Note that you can use boost::asio::placeholders::error in place of _1
// and boost::asio::bytes_transferred in place of _2.
socket_.async_receive(reply_buffer_.prepare(65536),
    boost::bind(&pinger::handle_receive, this, _1, _2));

同时更改handle_receive标头以接受错误代码

void handle_receive(const boost::system::error_code& error, std::size_t length) {
    if (error) {
        // Handle error
    }
    else {
        // Handle normally
    }
}

错误可能会传递到超时处理程序中。在这种情况下,您也可以检查其中的错误代码:

// Add _1 placeholder
timer_.async_wait(boost::bind(&pinger::handle_timeout, this, _1));

同样,您需要将该参数添加到处理程序中:

void handle_timeout(const boost::system::error_code& error) {
    if (error) {
        // Handle error
    }
    else {
        // Handle normally
    }
}