通过QtCreator,在C:\Users\Minwei\Projects\Qt路径下,创建名为HostInfo的控制台(Console)项目,并在项目文件中添加第2行:
xxxxxxxxxx
241QT -= gui
2QT += network
3
4CONFIG += c++11 console
5CONFIG -= app_bundle
6
7# The following define makes your compiler emit warnings if you use
8# any Qt feature that has been marked deprecated (the exact warnings
9# depend on your compiler). Please consult the documentation of the
10# deprecated API in order to know how to port your code away from it.
11DEFINES += QT_DEPRECATED_WARNINGS
12
13# You can also make your code fail to compile if it uses deprecated APIs.
14# In order to do so, uncomment the following line.
15# You can also select to disable deprecated APIs only up to a certain version of Qt.
16#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
17
18SOURCES += \
19main.cpp
20
21# Default rules for deployment.
22qnx: target.path = /tmp/$${TARGET}/bin
23else: unix:!android: target.path = /opt/$${TARGET}/bin
24!isEmpty(target.path): INSTALLS += target
C:\Users\Minwei\Projects\Qt\HostInfo\main.cpp:
xxxxxxxxxx
221
2using namespace std;
3
4
5
6
7
8int main(int argc, char *argv[])
9{
10 QCoreApplication a(argc, argv);
11
12 QString hostName = QHostInfo::localHostName();
13 cout << hostName.toStdString() << endl;
14
15 for (QHostAddress address : QHostInfo::fromName(hostName).addresses())
16 cout << QMetaEnum::fromType<
17 QAbstractSocket::NetworkLayerProtocol>().valueToKey(
18 address.protocol()) << ", " <<
19 address.toString().toStdString() << endl;
20
21 return a.exec();
22}
运行效果如图所示: