如何得到Ubuntu手机上的IP地址

88 阅读1分钟

在这篇文章中,我们介绍如何在Ubuntu QML应用中得到手机上的IP地址。

\

我们在我们的main.cpp中加入一些代码来得到IP地址:

\

main.cpp

\

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QNetworkInterface>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    QStringList datalist;

    for(int nIter = 0; nIter < list.count(); nIter++) {
        qDebug() << list[ nIter ].toString();
        datalist.append(list[ nIter ].toString());
    }

    QQuickView view;
    view.setSource(QUrl(QStringLiteral("qrc:///Main.qml")));
    view.setResizeMode(QQuickView::SizeRootObjectToView);

    QQmlContext *ctxt = view.rootContext();
    ctxt->setContextProperty("myModel", QVariant::fromValue(datalist));

    view.show();
    return app.exec();
}


\

Main.qml

\

import QtQuick 2.0
import Ubuntu.Components 1.1

/*!
    \brief MainView with a Label and Button elements.
*/

MainView {
    // objectName for functional testing purposes (autopilot-qt5)
    objectName: "mainView"

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "ipaddress.liu-xiao-guo"

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true

    // Removes the old toolbar and enables new features of the new header.
    useDeprecatedToolbar: false

    width: units.gu(60)
    height: units.gu(85)

    Page {
        title: i18n.tr("ipaddress")

        Column {
            spacing: units.gu(2)
            anchors {
                margins: units.gu(2)
                fill: parent
            }

            Label {
                id: label
                objectName: "label"
                fontSize: "large"

                text: i18n.tr("IP addresses: ")
            }

            ListView {
                width: parent.width
                height: parent.height - label.height
                model: myModel
                delegate: Text {
                    text: modelData
                }
            }

        }
    }
}


\

运行我们的应用:

\

\

\

这是我们在利用wifi时显示的IP地址。

\

我们的源码在:  github.com/liu-xiao-gu…