Make a ping function with QTcpSocket

回眸只為那壹抹淺笑 提交于 2020-06-01 07:40:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!