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

I am currently using this code to extract the ping of the target system. However, it still works only under Linux and probably depends on the locale settings. To add support for windows is likely to be even more difficult. Is there an easy way or library to get the ping of the 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 
+8
c ++ qt ping qtnetwork qabstractsocket
source share
3 answers

You will need to write your code for this without a QAbstractSocket . In short, this base class was not intended for this use case.

The reason is that you will need to use raw sockets and run them as root; therefore, you usually see the setuid flag set in the Linux ping executable.

ICMP is "connectionless", and therefore the Qt class is not possible for it, since it does not send data to a specific host, etc.

You can read a more detailed explanation here .

+2
source share

You can ping for 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 alive } else { // it dead } 
+12
source share

The awkward code didn’t work for me either. Perhaps this depends on Windows (tested on Windows 7 x64 + Qt 5.6). The Ping command seems to differ in parameters and values ​​and requires that they be separated when the QProcess is created.

Therefore, instead of skipping "-n 1" at a time, you will need to separately "-n" and "1".

Basically, with Nejat code, this will be:

 int exitCode = QProcess::execute("ping", QStringList() << "-n" << "1" << m_sHostName); if (exitCode==0) { // it alive } else { // it dead } 

Tested and working now.

+7
source share

All Articles