做菠菜網(wǎng)站有沒有被騙的百度瀏覽器官方網(wǎng)站
文章目錄
- 項目:網(wǎng)路
- 項目1:主機信息查詢
- 1.1 QHostInfo類和QNetworkInterface類
- 1.2 主機信息查詢項目實現(xiàn)
- 項目2:基于HTTP的網(wǎng)絡應用程序
- 2.1 項目中用到的函數(shù)詳解
- 2.2 主要源碼
項目:網(wǎng)路
項目1:主機信息查詢
使用QHostInfo類和QNetworkInterface類可以獲取主機的一些網(wǎng)絡信息,如IP地址1和MAC地址2。
在Qt項目里使用Qt Network模塊,需要在項目配置文件(.pro 文件)中增加一條配置語句:
QT += network
1.1 QHostInfo類和QNetworkInterface類
QHostInfo類常用函數(shù)
QHostInfo類可以根據(jù)主機名獲取主機的IP地址,或者通過IP地址獲取主機名。
- [static] QString QHostInfo::localHostName():返回本機主機名;
- [static] QString QHostInfo::localDomainName():返回本機域名系統(tǒng)(domain name system,DNS)域名;
- [static] QHostInfo QHostInfo::fromName(const QString &name):返回指定主機名的IP地址;
- [static] int QHostInfo::lookupHost(const QString &name, QObject *receiver, const char *member):以異步的方式根據(jù)主機名查找主機的IP地址,并返回一個表示本次查找的ID,可用作abortHostLookup()函數(shù)的參數(shù);
- [static] void QHostInfo::abortHostLookup(int id):使用 lookupHost() 返回的 ID 終止主機查找。
- QList<QHostAddress> QHostInfo::addresses() const:返回與hostName()對應主機關聯(lián)的IP地址列表;
- QString QHostInfo::hostName() const:返回通過IP地址查找到的主機名;
QNetworkInterface類常用的函數(shù)
QNetworkInterface類可以獲得運行程序的主機名的所用IP地址和網(wǎng)絡接口列表。
- [static] QList QNetworkInterface::allAddresses():返回主機上所有IP地址的列表(如果不需要知道子網(wǎng)掩碼和廣播地址);
- [static] QList QNetworkInterface::allInterfaces():返回主機上所有網(wǎng)絡接口列表(一個網(wǎng)絡接口可能包含多個IP地址,每個IP地址與掩碼或廣播地址關聯(lián));
- QList QNetworkInterface::addressEntries() const:返回網(wǎng)絡接口的IP地址列表,包括子網(wǎng)掩碼和廣播地址;
- QString QNetworkInterface::hardwareAddress() const:返回接口的低級硬件地址,以太網(wǎng)里就是MAC地址;
- bool QNetworkInterface::isValid() const:如果接口信息有效就返回true;
- QNetworkInterface::InterfaceType QNetworkInterface::type() const:返回網(wǎng)絡接口的類型;
1.2 主機信息查詢項目實現(xiàn)
- 顯示本機地址信息
//獲取本機主機名和IP地址按鈕
void Widget::on_btnGetHostInfo_clicked()
{ui->plainTextEdit->clear();QString hostName = QHostInfo::localHostName(); //本機主機名qDebug()<<hostName;ui->plainTextEdit->appendPlainText("HostName:"+hostName+"\n");QHostInfo hostInfo = QHostInfo::fromName(hostName); //本機IP地址QList<QHostAddress> addrList = hostInfo.addresses();//IP地址列表if(addrList.isEmpty()) return;foreach(QHostAddress host, addrList){bool show = ui->checkBox_OnlyIPV4->isChecked(); //只顯示ipv4//Returns the network layer protocol of the host address.show = show ? (host.protocol() == QAbstractSocket::IPv4Protocol):true;if(show){ui->plainTextEdit->appendPlainText("protool:"+protocolName(host.protocol()));//協(xié)議ui->plainTextEdit->appendPlainText("HostIPAdddress:"+host.toString());ui->plainTextEdit->appendPlainText(QString("isGolbal() = %1\n").arg(host.isGlobal()));}}
}
protocol()函數(shù):返回主機地址的網(wǎng)絡層協(xié)議。
QAbstractSocket::NetworkLayerProtocol QHostAddress::protocol() const
Returns the network layer protocol of the host address.
isGlobal()函數(shù):如果地址是 IPv4 或 IPv6 全局地址,則返回 true,否則返回 false。全局地址是不為特殊目的(如環(huán)回或多播)或未來目的保留的地址。
bool QHostAddress::isGlobal() const
Returns true if the address is an IPv4 or IPv6 global address, false otherwise. A global address is an address that is not reserved for special purposes (like loopback or multicast) or future purposes.
自定義函數(shù)protocolName(),通過協(xié)議類型返回協(xié)議名稱字符串。
//通過協(xié)議類型返回協(xié)議名稱字符串
QString Widget::protocolName(QAbstractSocket::NetworkLayerProtocol protocol)
{switch (protocol) {case QAbstractSocket::IPv4Protocol:return "IPV4";case QAbstractSocket::IPv6Protocol:return "IPV6";case QAbstractSocket::AnyIPProtocol:return "Any Internet Protocol";default:return "Unknown NetWork Layer Protocol";}
}
- 查找主機地址信息
[static] int QHostInfo::lookupHost(const QString &name, QObject *receiver, const char *member): name表示主機名的字符串,可以是主機名、域名或IP地址;receive和member指定接收者和槽函數(shù)名稱。
//查找域名的IP地址
void Widget::on_btnLookkup_clicked()
{ui->plainTextEdit->clear();QString hostName = ui->comboBox->currentText(); //讀取主機名ui->plainTextEdit->appendPlainText("Searching for host information:"+hostName+"\n");QHostInfo::lookupHost(hostName, this,SLOT(do_lookedUpHostInfo(QHostInfo)));
}//查找主機信息的槽函數(shù)
void Widget::do_lookedUpHostInfo(const QHostInfo &host)
{QList<QHostAddress> addrList = host.addresses(); //獲取主機地址列表if(addrList.isEmpty())return;foreach(QHostAddress host, addrList){bool show = ui->checkBox_OnlyIPV4->isChecked(); //只顯示ipv4//Returns the network layer protocol of the host address.show = show ? (host.protocol() == QAbstractSocket::IPv4Protocol):true;if(show){ui->plainTextEdit->appendPlainText("protool:"+protocolName(host.protocol()));//協(xié)議ui->plainTextEdit->appendPlainText(host.toString());ui->plainTextEdit->appendPlainText(QString("isGolbal() = %1\n").arg(host.isGlobal()));}}
}
- QNetworkInterface類的使用
//根據(jù)枚舉值返回字符串
QString Widget::interfaceType(QNetworkInterface::InterfaceType type)
{switch(type){case QNetworkInterface::Unknown:return "Unkown";case QNetworkInterface::Loopback:return "Loopback";case QNetworkInterface::Ethernet:return "Etherent";case QNetworkInterface::Wifi:return "Wifi";default:return "Other type";}
}//allInterfaces()
void Widget::on_btnAllInterface_2_clicked()
{ui->plainTextEdit->clear();QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();//網(wǎng)絡接口列表foreach(QNetworkInterface interface,list){if(!interface.isValid())continue;
// The name of the device
// Hardware devices
// Interface type
// Subnet mask
// broadcast addressui->plainTextEdit->appendPlainText("The name of the device:"+interface.humanReadableName());ui->plainTextEdit->appendPlainText("Hardware devices:"+interface.hardwareAddress());ui->plainTextEdit->appendPlainText("Interface type:"+interfaceType(interface.type()));QList<QNetworkAddressEntry> entryList = interface.addressEntries();//地址列表foreach(QNetworkAddressEntry entry, entryList){ui->plainTextEdit->appendPlainText(" IP Address:"+entry.ip().toString());ui->plainTextEdit->appendPlainText(" Subnet mask:"+entry.netmask().toString());ui->plainTextEdit->appendPlainText(" broadcast address:"+entry.broadcast().toString()+"\n");}}
}//alladdress
void Widget::on_btnAllAddress_clicked()
{ui->plainTextEdit->clear();QList<QHostAddress> addrelist = QNetworkInterface::allAddresses();//IP地址列表if(addrelist.isEmpty()) return;foreach(QHostAddress host, addrelist){bool show = ui->checkBox_OnlyIPV4->isChecked();show = show ? (host.protocol() == QAbstractSocket::IPv4Protocol):true;if(show){ui->plainTextEdit->appendPlainText("protocol:"+protocolName(host.protocol()));ui->plainTextEdit->appendPlainText("IP Address:"+host.toString());ui->plainTextEdit->appendPlainText(QString("isGrobal() = %1\n").arg(host.isGlobal()));}}
}
Loopback:
回送地址(Loopback Address)是本機回送地址(127.X.X.X),即主機IP堆棧內部的IP地址,主要用于網(wǎng)絡軟件測試以及本地機進程間通信。因此,無論什么程序,一旦使用回送地址發(fā)送數(shù)據(jù),協(xié)議軟件會立即將其返回,不進行任何網(wǎng)絡傳輸。127.0.0.1是回送地址,又指本地機,一般用來測試使用。
項目2:基于HTTP的網(wǎng)絡應用程序
QNetworkRequest 類通過 URL 發(fā)起網(wǎng)絡協(xié)議請求,其也保存網(wǎng)絡請求的信息,目前支持 HTTP、
FTP 和本地文件 URL 的下載或上傳。
QNetworkAccessManager 類用于協(xié)調網(wǎng)絡操作,在 QNetworkRequest 發(fā)起網(wǎng)絡請求后,
QNetworkAccessManager 負責發(fā)送網(wǎng)絡請求,以及創(chuàng)建網(wǎng)絡響應。
QNetworkReply 類表示網(wǎng)絡請求的響應,由 QNetworkAccessManager 在發(fā)送網(wǎng)絡請求后創(chuàng)建網(wǎng)
絡響應。QNetworkReply 提供的信號 finished()、readyRead()、downloadProgress()可用于監(jiān)測網(wǎng)絡響
應的執(zhí)行情況,從而進行相應的操作。
2.1 項目中用到的函數(shù)詳解
-
clearButtonEnabled : bool
此屬性用于保存行編輯在不為空時是否顯示清除按鈕。
如果啟用,行編輯在包含一些文本時會顯示一個尾隨清除按鈕,否則,行編輯不會顯示清除按鈕(默認值)。 -
默認路徑按鈕功能:
- [static] QString QDir::currentPath()
返回應用進程當前目錄的絕對路徑。當前目錄是使用 QDir::setCurrent() 設置的最后一個目錄,或者,如果從未調用過,則為父進程啟動此應用進程的目錄。 - bool QDir::mkdir(const QString &dirName) const
創(chuàng)建一個名為 dirName 的子目錄。
- 下載按鈕功能:
- QString QString::trimmed() const
返回一個字符串,該字符串刪除了開頭和結尾的空格。 - [static] QUrl QUrl::fromUserInput(const QString &userInput)
從用戶提供的 userInput 字符串返回有效的 URL(如果可以扣除)。如果不可能,則返回無效的 QUrl()。 - QString QUrl::errorString() const
如果修改此 QUrl 對象的最后一個操作遇到解析錯誤,則返回錯誤消息。如果未檢測到錯誤,則此函數(shù)返回一個空字符串,isValid() 返回 true。 - QString QUrl::fileName(QUrl::ComponentFormattingOptions options = FullyDecoded) const
返回文檔名,不包括目錄路徑。 - bool QFile::remove()
刪除 fileName() 指定的文檔。如果成功,則返回 true;否則返回 false。文檔在刪除之前已關閉。 - QNetworkReply *QNetworkAccessManager::get(const QNetworkRequest &request)
發(fā)布一個請求以獲取目標請求的內容,并返回一個新的 QNetworkReply 對象,該對象打開以供讀取,每當新數(shù)據(jù)到達時,該對象都會發(fā)出 readyRead() 信號。將下載內容以及相關的標題。 - [signal] void QIODevice::readyRead()
每當有新數(shù)據(jù)可用時,此信號就會發(fā)出一次從設備的當前讀取信道讀取。只有當有新數(shù)據(jù)可用時,它才會再次發(fā)出,例如,當新的網(wǎng)絡數(shù)據(jù)有效負載到達您的網(wǎng)絡套接字時,或者當新的數(shù)據(jù)塊附加到您的設備時。 - [signal] void QNetworkReply::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
發(fā)出此信號以指示此網(wǎng)絡請求的下載部分的進度(如果有)。如果沒有與此請求關聯(lián)的下載,則此信號將發(fā)出一次,其中 0 作為 bytesReceived 和 bytesTotal 的值。 - [signal] void QNetworkReply::finished()
當回復完成處理時,將發(fā)出此信號。發(fā)出此信號后,回復的數(shù)據(jù)或元數(shù)據(jù)將不再更新。
- 讀取下載數(shù)據(jù)
-
qint64 QIODevice::write(const char *data, qint64 maxSize)
將數(shù)據(jù)中最多 maxSize 字節(jié)的數(shù)據(jù)寫入設備。返回實際寫入的字節(jié)數(shù),如果發(fā)生錯誤,則返回 -1。 -
QByteArray QIODevice::readAll()
從設備讀取所有剩余數(shù)據(jù),并將其作為字節(jié)數(shù)組返回。
2.2 主要源碼
頭文件
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QNetworkAccessManager>
#include <QFile>
#include <QMessageBox>
#include <QIODevice>
#include <QNetworkReply>
#include <QDesktopServices>
#include <QFileInfo>
#include <QUrl>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECT
private:QNetworkAccessManager networkManager; //網(wǎng)絡管理QNetworkReply *reply; //網(wǎng)絡響應QFile *downloadedFile; //下載保存的臨時文件
public:explicit Widget(QWidget *parent = nullptr);~Widget();
private slots:void do_finished();void do_readyRead();void do_downloadProgress(qint64 bytesRead, qint64 totalBytes);void on_btnDownload_clicked();void on_btnDefaultPath_clicked();void on_editURL_textChanged(const QString &arg1);private:Ui::Widget *ui;
};#endif // WIDGET_H
源文件
#include "widget.h"
#include "ui_widget.h"#include <QDir>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);
//clearButtonEnabled : bool
//This property holds whether the line edit displays a clear button when it is not empty.
//If enabled, the line edit displays a trailing clear button when it contains some text,
// otherwise the line edit does not show a clear button (the default).ui->editURL->setClearButtonEnabled(true);this->setLayout(ui->verticalLayout);
}Widget::~Widget()
{delete ui;
}void Widget::do_finished()
{//網(wǎng)絡響應結束QFileInfo fileInfo(downloadedFile->fileName()); //獲取下載文件的文件名downloadedFile->close();delete downloadedFile; //刪除臨時文件reply->deleteLater(); //由主事件循環(huán)刪除此文件對象if(ui->checkBoxOpen->isChecked()){QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absoluteFilePath()));}ui->btnDownload->setEnabled(true);
}void Widget::do_readyRead()
{//讀取下載數(shù)據(jù)downloadedFile->write(reply->readAll());
// qint64 QIODevice::write(const char *data, qint64 maxSize)
// Writes at most maxSize bytes of data from data to the device.
// Returns the number of bytes that were actually written,
// or -1 if an error occurred.
// QByteArray QIODevice::readAll()
// Reads all remaining data from the device, and returns it as a byte array.}void Widget::do_downloadProgress(qint64 bytesRead, qint64 totalBytes)
{//下載進度ui->progressBar->setMaximum(totalBytes);//Holds the total amount of data to download in bytes.ui->progressBar->setValue(bytesRead);
}//默認了路徑 按鈕
void Widget::on_btnDefaultPath_clicked()
{
// [static] QString QDir::currentPath()
// Returns the absolute path of the application's current directory.
// The current directory is the last directory set with QDir::setCurrent() or,
// if that was never called,
// the directory at which this application was started at by the parent process.QString curPath = QDir::currentPath(); //返回當前絕對路徑給QString變量QDir dir(curPath); //定義QDir變量QString sub = "temp";
// bool QDir::mkdir(const QString &dirName) const
// Creates a sub-directory called dirName.dir.mkdir(sub); //當前路徑下創(chuàng)立名為sub的文件夾ui->editPath->setText(curPath+"/"+sub+"/"); //設置lineedit的文字
}//下載按鈕,開始下載
void Widget::on_btnDownload_clicked()
{
// QString QString::trimmed() const
// Returns a string that has whitespace removed from the start and the end.QString urlSpec = ui->editURL->text().trimmed(); //將editURL中的文字給QString變量賦值//urlspec判空if(urlSpec.isEmpty()){QMessageBox::information(this,"error","Please specify the download address");return;}
// [static] QUrl QUrl::fromUserInput(const QString &userInput)
// Returns a valid URL from a user supplied userInput string if one can be deducted.
// In the case that is not possible, an invalid QUrl() is returned.QUrl newUrl = QUrl::fromUserInput(urlSpec); //從urlSpaec里獲取url//newurl判有效if(!newUrl.isValid()){
// QString QUrl::errorString() const
// Returns an error message if the last operation that modified this QUrl object ran into a parsing error.
// If no error was detected,
// this function returns an empty string and isValid() returns true.QString info = "The URL is invalid:"+urlSpec+"\n error:"+newUrl.errorString();QMessageBox::information(this,"error",info);return;}QString tempDir = ui->editPath->text().trimmed(); //臨時目錄if(tempDir.isEmpty()){QMessageBox::information(this,"error","Please specify the download address");return;}QString fullFileName = tempDir + newUrl.fileName(); //文件名
// QString QUrl::fileName(QUrl::ComponentFormattingOptions options = FullyDecoded) const
// Returns the name of the file, excluding the directory path.if(QFile::exists(fullFileName)){ //如果文件存在QFile::remove(fullFileName); //刪除文件
// bool QFile::remove()
// Removes the file specified by fileName(). Returns true if successful; otherwise returns false.
// The file is closed before it is removed.}downloadedFile = new QFile(fullFileName); //創(chuàng)建臨時文件if(!downloadedFile->open(QIODevice::WriteOnly)){QMessageBox::information(this,"error","Temporary file open error");}ui->btnDownload->setEnabled(false);//發(fā)送網(wǎng)絡請求,創(chuàng)建網(wǎng)絡相應reply = networkManager.get(QNetworkRequest(newUrl)); //網(wǎng)絡響應從網(wǎng)絡管理里面獲取網(wǎng)絡請求
// QNetworkReply *QNetworkAccessManager::get(const QNetworkRequest &request)
// Posts a request to obtain the contents of the target request and
// returns a new QNetworkReply object opened for reading
// which emits the readyRead() signal whenever new data arrives.
// The contents as well as associated headers will be downloaded.
// QObject *QObject::parent() const
// Returns a pointer to the parent object.connect(reply, SIGNAL(readyRead()), this, SLOT(do_readyRead()));connect(reply, SIGNAL(downloadProgress(qint64,qint64)),this, SLOT(do_downloadProgress(qint64,qint64)));connect(reply, SIGNAL(finished()), this, SLOT(do_finished()));
// [signal] void QIODevice::readyRead()
// This signal is emitted once every time new data is available for
// reading from the device's current read channel.
// It will only be emitted again once new data is available,
// such as when a new payload of network data has arrived on your network socket,
// or when a new block of data has been appended to your device.
// [signal] void QNetworkReply::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
// This signal is emitted to indicate the progress of the download part of
// this network request, if there's any. If there's no download associated with this request,
// this signal will be emitted once with 0 as the value of both bytesReceived and bytesTotal.
// [signal] void QNetworkReply::finished()
// This signal is emitted when the reply has finished processing.
// After this signal is emitted, there will be no more updates to the reply's data or metadata.
}void Widget::on_editURL_textChanged(const QString &arg1)
{Q_UNUSED(arg1);ui->progressBar->setMaximum(100);ui->progressBar->setValue(0);
}
IP地址(Internet Protocol Address)是指互聯(lián)網(wǎng)協(xié)議地址,又譯為網(wǎng)際協(xié)議地址。IP地址是IP協(xié)議提供的一種統(tǒng)一的地址格式,它為互聯(lián)網(wǎng)上的每一個網(wǎng)絡和每一臺主機分配一個邏輯地址,以此來屏蔽物理地址的差異。 ??
MAC地址(英語:Media Access Control Address),直譯為媒體存取控制位址,也稱為局域網(wǎng)地址(LAN Address),MAC位址,以太網(wǎng)地址(Ethernet Address)或物理地址(Physical Address),它是一個用來確認網(wǎng)絡設備位置的位址。在OSI模型中,第三層網(wǎng)絡層負責IP地址,第二層數(shù)據(jù)鏈路層則負責MAC位址。MAC地址用于在網(wǎng)絡中唯一標示一個網(wǎng)卡,一臺設備若有一或多個網(wǎng)卡,則每個網(wǎng)卡都需要并會有一個唯一的MAC地址。 ??