以下是我根据boost asio测量ping时间的代码:
void PingServiceImpl::pingHost( const std::string& remoteIp,
const PingService::TimeDuration& timeout )
{
sendRequestTo(remoteIp, timeout);
receiveResponseFrom(remoteIp);
}
void PingServiceImpl::sendRequestTo(const std::string& remoteIp, const TimeDuration& timeout)
{
boost::asio::ip::icmp::resolver remoteEndpointResolver(m_ioService);
boost::asio::ip::icmp::endpoint remoteEndpoint = *remoteEndpointResolver.resolve(boost::asio::ip::icmp::resolver::query(boost::asio::ip::icmp::v4(), remoteIp.c_str(), ""));
std::string body = "icmp request to " + remoteIp;
IcmpHeader echoRequest;
echoRequest.type(IcmpHeader::echo_request);
echoRequest.code(0);
echoRequest.identifier(getProcId());
echoRequest.sequence_number(++m_sequenceNumber);
boost::uint16_t checksum = compute_checksum( echoRequest,
body.begin(),
body.end());
echoRequest.checksum(checksum);
boost::asio::streambuf requestBuffer;
std::ostream outStream(&requestBuffer);
outStream << echoRequest << body;
m_timeBeforeRequestSend = boost::posix_time::microsec_clock::universal_time();
m_socket.send_to(requestBuffer.data(), remoteEndpoint);
m_timer.expires_at(m_timeBeforeRequestSend + timeout);
m_timer.async_wait(boost::bind(&PingServiceImpl::handleTimeout, this));
}
void PingServiceImpl::receiveResponseFrom(const std::string& remoteIp)
{
m_replyBuffer.consume(m_replyBuffer.size());
m_socket.async_receive(m_replyBuffer.prepare(65536),
boost::bind(&PingServiceImpl::handleReceiveResponse, this, _1, remoteIp, _2));
}
void PingServiceImpl::handleReceiveResponse( const boost::system::error_code& error,
std::string remoteIp,
std::size_t responseSize)
{
if(!error)
{
m_replyBuffer.commit(responseSize);
std::istream inputStream(&m_replyBuffer);
ipv4_header ipv4Header;
IcmpHeader icmpHeader;
inputStream >> ipv4Header >> icmpHeader;
std::string expectedBody = "icmp request to " + remoteIp;
if (icmpHeader.type() == IcmpHeader::echo_reply
&& icmpHeader.identifier() == getProcId()
&& icmpHeader.sequence_number() == m_sequenceNumber
&& icmpHeader.checksum() == compute_checksum(icmpHeader, expectedBody.begin(), expectedBody.end()))
{
m_timer.cancel();
m_timeAfterResponseReceive = boost::posix_time::microsec_clock::universal_time();
boost::system::error_code ec = boost::system::errc::make_error_code(boost::system::errc::success);
this->m_pingHandler( m_timeAfterResponseReceive - m_timeBeforeRequestSend, ec );
}
}
}
m_timeAfterResponseReceive - 是获取RX消息的当前时间 m_timeBeforeRequestSend - 是TX发生的当前时间
有了这个,我得到ping时间= 0.这怎么可能?甚至Windows cmd ping实用程序为localhost提供1 ms。我做错了什么?
BR, 梅德