QT区别有线网络和无线网络IP地址

原文地址

原文链接

前言

QT下获取可用IP地址比较简单,一般的实现方法为

void IndexWidget::updateMsg()
{
    // update ip
    bool                hasLink   = false;
    const QHostAddress& localhost = QHostAddress(QHostAddress::LocalHost);
    for (const QHostAddress& address : QNetworkInterface::allAddresses())
    {
        if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost)
        {
            hasLink = true;
            lineLabel->setText(QString::fromUtf8("IP: ") + address.toString());
        }
    }
    if (!hasLink)
    {
        lineLabel->setText(QString::fromUtf8("IP: 无连接"));
    }
    // ...
}

但是这种方式无法区别有线和无线,有线和无线的区分可以使用addressEntries来代替allAddresses进行循环迭代

实现

具体代码如下

void IndexWidget::updateMsg()
{
    // update ip
    bool hasWired    = false;
    bool hasWireless = false;
    for (const QNetworkInterface& address : QNetworkInterface::allInterfaces())
    {
        if (!address.flags().testFlag(QNetworkInterface::IsRunning))
        {
            continue;
        }
        for (const QNetworkAddressEntry& entry : address.addressEntries())
        {
            if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol && entry.ip() != QHostAddress(QHostAddress::LocalHost))
            {
                if (address.type() == QNetworkInterface::Wifi)
                {
                    hasWireless = true;
                    wifiLabel->setText(QString::fromUtf8("无线: ") + entry.ip().toString());
                }
                else
                {
                    hasWired = true;
                    lineLabel->setText(QString::fromUtf8("有线: ") + entry.ip().toString());
                }
            }
        }
    }
    if (!hasWired)
    {
        lineLabel->setText(QString::fromUtf8("有线:无连接"));
    }
    if (!hasWireless)
    {
        wifiLabel->setText(QString::fromUtf8("无线:无连接"));
    }
    // ...
}

顺便贴上相关官方文档QNetworkInterface Class以供更多需求查询

补充

我们可以看到QNetworkInterface::type() const这个函数是在5.11版本中引入的,那么之前版本的小伙伴应该怎么办呢。我目前想到的方案只有写死网卡名称,比如一般的eth0这种,如果是独立开发运行的机器也可以按照MAC地址判断,如果有大家有更好的方案可以评论区提出

原文地址

原文链接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值