问题
I want to make a ping function with Qt (and don't like the QProcess execution system ping way).
Here's the demo code,
void SimmplePing(const QString& sAddress, int port=80)
{
QTcpSocket messenger;
messenger.connectToHost(sAddress, port);
if (!messenger.waitForConnected(3000))
{
qDebug() << messenger.error();
}
else
{
qDebug() << "OK";
}
}
void test()
{
SimmplePing("182.34.19.222", 80);
}
I test it with "192.168.0.1" (my router IP) and "www.baidu.com" both can work.
But I test it "182.34.19.222" failed with QAbstractSocket::SocketTimeoutError
error message.
However, pinging it within system cmd can work properly. Couldn't figure out why.
回答1:
The main difference here is that the ping command as it's normally used, uses the ICMP protocol which doesn't use TCP for communication. Trying to connect to a host via websockets using TCP is handled in a different way. If the TCP socket of the host you're trying to connect to doesn't listen on the specified port, in this case port 80, you won't recieve an answer, which can lead to the behaviour you encountered.
(https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol)
来源:https://stackoverflow.com/questions/62082192/make-a-ping-function-with-qtcpsocket