C++ | Qt 获取局域网中存在的主机(IP以及主机名)
生活随笔
收集整理的這篇文章主要介紹了
C++ | Qt 获取局域网中存在的主机(IP以及主机名)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
原理
演示
?
?
原理
這里主要是通過QHostInfo::lookupHost獲取主機名,當然也可以通過IP找主機名,只要遍歷局域網IP看其是否有主機名,就可以知道,這個IP是不是被使用(但是,某些開防火墻的機子,使用了IP,也是不能找到的)
這里有個小知識點這個和QHostInfo::lookupHost不一樣,使用arp會準確很多,后期將會給出arp去掃描局域網使用的IP:
?
演示
程序運行如下:
程序結構如下:
widget.h
#ifndef WIDGET_H #define WIDGET_H#include <QWidget>QT_BEGIN_NAMESPACE class QHostInfo; QT_END_NAMESPACEnamespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();protected slots:void lookUp(const QHostInfo &host);void btnClicked();private:Ui::Widget *ui; };#endif // WIDGET_Hmain.cpp
#include "widget.h" #include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); }widget.cpp
#include "widget.h" #include "ui_widget.h" #include <QHostAddress> #include <QHostInfo> #include <QDebug>#define Col1 0 #define Col2 1Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget) {ui->setupUi(this);//this->setWindowTitle("CSDN IT1995");ui->tableWidget->horizontalHeader()->setStretchLastSection(true);ui->tableWidget->setRowCount(255);connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(btnClicked())); }Widget::~Widget() {delete ui; }int useRow = 0;void Widget::lookUp(const QHostInfo &host) {if(host.error() != QHostInfo::NoError){qDebug() << "Lookup failed:" << host.errorString();return;}if(host.addresses()[0].toString() == host.hostName())return;QTableWidgetItem *ipItem = new QTableWidgetItem;ipItem->setText(host.addresses()[0].toString());QTableWidgetItem *hostItem = new QTableWidgetItem;hostItem->setText(host.hostName());if(ipItem->text() != hostItem->text()){ipItem->setTextColor(QColor(Qt::red));hostItem->setTextColor(QColor(Qt::red));}ui->tableWidget->setItem(useRow, Col1, ipItem);ui->tableWidget->setItem(useRow, Col2, hostItem);useRow++; }void Widget::btnClicked() {for(int i = 1 ; i < 256; i++){QHostInfo::lookupHost(QString("192.1.101.%1").arg(i), this, SLOT(lookUp(QHostInfo)));} }源碼打包下載地址:
https://github.com/fengfanchen/Qt/tree/master/getLANUser
總結
以上是生活随笔為你收集整理的C++ | Qt 获取局域网中存在的主机(IP以及主机名)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot三合一实验(添加人
- 下一篇: Java通过反射了解集合泛型的本质(Cl