QHostInfo检测网络

这篇博客介绍了如何使用QHostInfo在Qt中检测网络状态,通过代码示例展示了在网络断开后仍然返回true的问题。作者分析了QHostInfo可能存在的缓存机制,并发现无法直接清除缓存。为了解决这个问题,作者建议自行实现ping操作,利用QtConcurrent进行多线程处理,以避免阻塞界面。

   平时,我们检测网络是否连接,一般都是用ping命令。实际开发中,经常也需要检测网络状态。最近之项目过程中就需要实现这一的功能,在网络断开时给出相应的用户提示。QHostInfo给我们提供了一个方便的接口,实现这一的功能。话不多说,先上一段代码demo


NetWorkTest *NetWorkTest::GetInstance()
{
    static NetWorkTest instance;
    return &instance;
}

void NetWorkTest::checkNetWork()
{
    QHostInfo::lookupHost("www.baidu.com",this,SLOT(lookedUpSlot(QHostInfo)));
    qDebug()<< "lookupHost";
}

NetWorkTest::NetWorkTest(QObject *parent) : QObject(parent)
{

}


void NetWorkTest::lookedUpSlot(QHostInfo hostInfo)
{
    qDebug()<<__FUNCTION__;
    bool status = false;
    if(hostInfo.error() == QHostInfo::NoError)
    {
        status = true;
    }
    emit netWorkStateChanged(status);
}


//main.cpp

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值