ping-c++的丢包测量

Posted

技术标签:

【中文标题】ping-c++的丢包测量【英文标题】:Measuring packet loss of ping- c++ 【发布时间】:2013-05-30 13:25:51 【问题描述】:

我需要编写 C++ 代码来测量 ping 的丢包率——丢包的百分比。 我看到IPHLPAPI 库有很多关于 RTT 的统计信息,但没有丢包。

如果有人对此有所了解,那就太好了!

谢谢。

【问题讨论】:

您的问题需要一个更明确的目标来确定您的实际问题。到目前为止你做了什么,你不确定什么? 好的。我有将 ping 发送到特定 IP 地址的代码。在 ICMP 响应中,有一个包含所有相关参数的结构,例如 RTT、DataSize ......但我还需要该 ping 的数据包丢失。我希望它更清楚一点。 前段时间我做过这个,我只是在标准 ping 之上使用了一个小脚本,该脚本在接收数据包的时间之前计算“丢失”数据包的数量。但是,如果您编写自己的代码,您只需发送一个数据包,然后等待回复回来。如果 X 秒内没有回复,则为“丢失”数据包。 (这里的X可能不是整数) 【参考方案1】:

您可以使用 POCO 库,它很小(比 boost 小很多)并且在网络方面比 ACE 更具可读性。

这里是使用 ICMPClient 的 ping 程序的源代码 你会在 POCO_BASE/net/examples/Ping/src 下找到它

#include "Poco/Util/Application.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/Util/AbstractConfiguration.h"
#include "Poco/Net/ICMPSocket.h"
#include "Poco/Net/ICMPClient.h"
#include "Poco/Net/IPAddress.h"
#include "Poco/Net/ICMPEventArgs.h"
#include "Poco/AutoPtr.h"
#include "Poco/NumberParser.h"
#include "Poco/Delegate.h"
#include <iostream>
#include <sstream>


using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter;
using Poco::Util::AbstractConfiguration;
using Poco::Net::ICMPSocket;
using Poco::Net::ICMPClient;
using Poco::Net::IPAddress;
using Poco::Net::ICMPEventArgs;
using Poco::AutoPtr;
using Poco::NumberParser;
using Poco::Delegate;


class Ping: public Application
    /// This sample demonstrates the Poco::Net::ICMPClient in conjunction with 
    /// Poco Foundation C#-like events functionality.
    ///
    /// Try Ping --help (on Unix platforms) or Ping /help (elsewhere) for
    /// more information.

public:
    Ping(): 
        _helpRequested(false), 
        _icmpClient(IPAddress::IPv4),
        _repetitions(4), 
        _target("localhost")
    
    

protected:  
    void initialize(Application& self)
    
        loadConfiguration(); // load default configuration files, if present
        Application::initialize(self);

        _icmpClient.pingBegin += Delegate<Ping, ICMPEventArgs>(this, &Ping::onBegin);
        _icmpClient.pingReply += Delegate<Ping, ICMPEventArgs>(this, &Ping::onReply);
        _icmpClient.pingError += Delegate<Ping, ICMPEventArgs>(this, &Ping::onError);
        _icmpClient.pingEnd   += Delegate<Ping, ICMPEventArgs>(this, &Ping::onEnd);
    

    void uninitialize()
    
        _icmpClient.pingBegin -= Delegate<Ping, ICMPEventArgs>(this, &Ping::onBegin);
        _icmpClient.pingReply -= Delegate<Ping, ICMPEventArgs>(this, &Ping::onReply);
        _icmpClient.pingError -= Delegate<Ping, ICMPEventArgs>(this, &Ping::onError);
        _icmpClient.pingEnd   -= Delegate<Ping, ICMPEventArgs>(this, &Ping::onEnd);

        Application::uninitialize();
    

    void defineOptions(OptionSet& options)
    
        Application::defineOptions(options);

        options.addOption(
            Option("help", "h", "display help information on command line arguments")
                .required(false)
                .repeatable(false));

        options.addOption(
            Option("repetitions", "r", "define the number of repetitions")
                .required(false)
                .repeatable(false)
                .argument("repetitions"));

        options.addOption(
            Option("target", "t", "define the target address")
                .required(false)
                .repeatable(false)
                .argument("target"));
    

    void handleOption(const std::string& name, const std::string& value)
    
        Application::handleOption(name, value);

        if (name == "help")
            _helpRequested = true;
        else if (name == "repetitions")
            _repetitions = NumberParser::parse(value);
        else if (name == "target")
            _target = value;
    

    void displayHelp()
    
        HelpFormatter helpFormatter(options());
        helpFormatter.setCommand(commandName());
        helpFormatter.setUsage("OPTIONS");
        helpFormatter.setHeader(
            "A sample application that demonstrates the functionality of the "
            "Poco::Net::ICMPClient class in conjunction with Poco::Events package functionality.");
        helpFormatter.format(std::cout);
    


    int main(const std::vector<std::string>& args)
    
        if (_helpRequested) 
            displayHelp();
        else 
            _icmpClient.ping(_target, _repetitions);

        return Application::EXIT_OK;
    


    void onBegin(const void* pSender, ICMPEventArgs& args)
    
        std::ostringstream os;
        os << "Pinging " << args.hostName() << " [" << args.hostAddress() << "] with " << args.dataSize() << " bytes of data:" 
           << std::endl << "---------------------------------------------" << std::endl;
        logger().information(os.str());
    

    void onReply(const void* pSender, ICMPEventArgs& args)
    
        std::ostringstream os;
        os << "Reply from " << args.hostAddress()
           << " bytes=" << args.dataSize() 
           << " time=" << args.replyTime() << "ms"
           << " TTL=" << args.ttl();
        logger().information(os.str());
    

    void onError(const void* pSender, ICMPEventArgs& args)
    
        std::ostringstream os;
        os << args.error();
        logger().information(os.str());
    

    void onEnd(const void* pSender, ICMPEventArgs& args)
    
        std::ostringstream os;
        os << std::endl << "--- Ping statistics for " << args.hostName() << " ---"
           << std::endl << "Packets: Sent=" << args.sent() << ", Received=" << args.received()
           << " Lost=" << args.repetitions() - args.received() << " (" << 100.0 - args.percent() << "% loss),"
           << std::endl << "Approximate round trip times in milliseconds: " << std::endl
           << "Minimum=" << args.minRTT() << "ms, Maximum=" << args.maxRTT()  
           << "ms, Average=" << args.avgRTT() << "ms" 
           << std::endl << "------------------------------------------";
        logger().information(os.str());
    

private:
    bool        _helpRequested;
    ICMPClient  _icmpClient;
    int         _repetitions;
    std::string _target;
;


int main(int argc, char** argv)

    AutoPtr<Ping> pApp = new Ping;
    try
    
        pApp->init(argc, argv);
    
    catch (Poco::Exception& exc)
    
        pApp->logger().log(exc);
        return Application::EXIT_CONFIG;
    
    return pApp->run();

您可以删除记录器/帮助内容以缩短源代码并使用 OnReply / OnError / OnEnd 计算丢包率

您发送 4 个数据包 .... 3 个数据包被退回 (OnReply) 数据包丢失 = 1-3/4 = 25%。

【讨论】:

谢谢!我会试试看。 POCO_BASE 库在哪里?它已经在我的电脑上了吗?需要下载吗?

以上是关于ping-c++的丢包测量的主要内容,如果未能解决你的问题,请参考以下文章

零丢包率的丢包层

WireShark 查看UDP码流的丢包率

用cacti监测全国的各省市的骨干网络的丢包率,我怎么能让这些丢包率显示在气象图上呢? 求教

服务器网卡丢包

iOS Ble开发丢包问题

shell-004:检测机器存活或者网络陡动情况!