Qt函数及库的运用
Nevermore 2025-07-03 OS
# 1. 基本知识
# 网络库
- QHostInfo / QNetworkInterface
- 获取本地主机名称和ip
#include <QHostInfo>
#include <QNetworkInterface>
void Widget::GetHostNameAndIp()
{
QString strLocal = QHostInfo::localHostName(); //Get Host PC Name
QString strLoacalAddr = ""; // Get Host PC IP addr by name
QHostInfo hostInfo = QHostInfo::fromName(strLocal);
QList<QHostAddress> ipaddrList = hostInfo.addresses();
if(!ipaddrList.isEmpty())
{
for(int i = 0; i < ipaddrList.size(); i++)
{
QHostAddress addrHost = ipaddrList.at(i);
if(QAbstractSocket::IPv4Protocol == addrHost.protocol())
{
strLoacalAddr = addrHost.toString();
break;
}
}
}
qDebug() << strLocal << strLoacalAddr;
QString temp = "";
QList<QNetworkInterface> netList = QNetworkInterface::allInterfaces();
for(int i = 0; i < netList.size(); i++)
{
QNetworkInterface interfaces = netList.at(i);
qDebug() << "设备名称:" << interfaces.name();
qDebug() << "硬件地址:" << interfaces.hardwareAddress();
QList<QNetworkAddressEntry> entrylist = interfaces.addressEntries();
for(int j = 0; j < entrylist.size(); j++)
{
QNetworkAddressEntry enter = entrylist.at(j);
qDebug() << "IP地址:" << enter.ip().toString();
qDebug() << "子网掩码:" << enter.netmask().toString();
qDebug() << "广播地址:" << enter.broadcast().toString();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
- 获取域名对应的主机ip
QString Widget::ProtocolType(QAbstractSocket::NetworkLayerProtocol protocal)
{
switch(protocal)
{
case QAbstractSocket::IPv4Protocol:
return "IPv4Protocol";
break;
case QAbstractSocket::IPv6Protocol:
return "IPv6Protocol";
break;
case QAbstractSocket::AnyIPProtocol:
return "AnyIPProtocol";
break;
case QAbstractSocket::UnknownNetworkLayerProtocol:
return "UnknownNetworkLayerProtocol";
break;
default:
break;
}
return "";
}
private slots:
void Widget::GetIpList(const QHostInfo &host)
{
QList<QHostAddress> ipaddrList = host.addresses();
for(int i = 0; i < ipaddrList.size(); i++)
{
QHostAddress host = ipaddrList.at(i);
qDebug() << "协议类型:" << ProtocolType(host.protocol());
qDebug() << "本地Ip地址:" << host.toString();
}
}
QString domainName = "www.baidu.com";
QHostInfo::lookupHost(domainName, this, SLOT(GetIpList(QHostInfo)));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45