Get the ping from a remote target with Qt (Windows/Linux)

dgrat picture dgrat · Apr 8, 2014 · Viewed 16.7k times · Source

Currently I use this code for retrieving the ping of a target system. However it works so far only under linux and it is likely dependent on the locale settings. To add support for windows will be likely even more complicated. Is there an easy way or library to get the ping of a target system? I mainly work with Qt, so it would be ideal if I could work with QSockets.

#ifndef _WIN32
QProcess ping;
ping.start("ping", QStringList() << "-c 1" << m_sHostName);
if(ping.waitForFinished(250) ) {
    while(ping.canReadLine()) {
        QString line = ping.readLine();
        if(line.contains("time=")) {
            int iStart = line.indexOf("time=") + 5;
            int iStop = line.indexOf(" ms");
            QStringRef latency(&line, iStart, iStop-iStart);

            m_vNetwork_s.append(time_s);
            m_vLatency_ms.append(QString(latency.toLocal8Bit()).toDouble());
            break;
        }
    }
}
#endif

Answer

Nejat picture Nejat · Apr 8, 2014

You can ping on both Windows and Linux using this:

   QStringList parameters;
#if defined(WIN32)
   parameters << "-n" << "1";
#else
   parameters << "-c 1";
#endif

   parameters << m_sHostName;

   int exitCode = QProcess::execute("ping", parameters);
   if (exitCode==0) {
       // it's alive
   } else {
       // it's dead
   }