使用Qt检查IP活动地址

时间:2017-07-13 13:24:44

标签: qt networking ip

我需要检查局域网中的所有活动IP地址。 我试过这段代码:

void MainWindow::on_pushButton_clicked() {
QString baseNetowrk = "192.168.1.";
for(int i = 0;i < 255;i++) {
    QString currIp = (baseNetowrk + "%1").arg(i);
    //qDebug() << "IP: " << currIp;
    QHostInfo hostInfo = QHostInfo::fromName(currIp);
    qDebug() << "NOME: " << hostInfo.hostName();
}

}

但这显示了所有IP(我认为在ARP缓存中) 我怎样才能显示活动的IP?

2 个答案:

答案 0 :(得分:0)

所有ip地址

   foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) {
            if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost))
                 qDebug() << address.toString();
        }

或ARP扫描

 QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
        for(int i = 0; i < ipAddressesList.size(); ++ i) {
           if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
               ipAddressesList.at(i).toIPv4Address()) {
               ipAddress = ipAddressesList.at(i).toString();
               if(ipAddress.left(3) == "192") {
                   break;
               }
           }
       }

 ipAddress = ipAddress.left(ipAddress.lastIndexOf(".") + 1);

      for(int i = 0; i <= 255; ++i ) {
            m_socketsPool.append(new QTcpSocket(this));
            QString currentHost = ipAddress + QString::number(i);
            connect(m_socketsPool.at(i), SIGNAL(readyRead()), this, SLOT(readFortune()));
            connect(m_socketsPool.at(i), SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
            m_socketsPool.at(i)->connectToHost(currentHost, yourHost);


   }




void readFortune()
{
    int i = 0;
    for(; i < m_socketsPool.size(); ++i) {
        if(sender() == m_socketsPool.at(i)) {
            QString currentHost = ipAddress + QString::number(i);
            qDebug()<<currentHost;
            ipStringList +=(QStringList() << currentHost);
            break;
        }
    }

    emit onOutStr(ipStringList);
}

答案 1 :(得分:0)

好的,这段代码有效:

void MainWindow::on_pushButton_clicked() {
    QString baseNetowrk = "192.168.1.";
#if defined(WIN32)
    QString parameter = "-n 1";
#else
    QString parameter = "-c 1";
#endif
    for(int i = 0; i < 256; i++) {
        QString currIp(baseNetowrk + QString::number(i));
        int exitCode = QProcess::execute("ping", QStringList() << parameter << currIp);
        if (exitCode == 0) {
            qDebug() << "OK :" << baseNetowrk + i;
        } else {
            qDebug() << "KO";
        }
    }
}

唯一的问题是它有点慢......