Getting MAC ID in Qt
Asked Answered
R

1

5

I am using the following code to get the MAC ID in Qt.

main.cpp

#include <QtCore/QCoreApplication>
#include "QtNetwork/QNetworkInterface"
#include "QString"

QString getMacAddress()
{
    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
    {
        // Return only the first non-loopback MAC Address
        if (!(interface.flags() & QNetworkInterface::IsLoopBack))
            return interface.hardwareAddress();
        QString text = interface.hardwareAddress();
        qDebug() << text;
    }
    return QString();
}

int main(int argc, char *argv[])
{
    getMacAddress();
    QCoreApplication a(argc, argv);
    return a.exec();
}

I am getting nothing in Console? Guide me thanks...

Rhotacism answered 8/3, 2013 at 6:10 Comment(10)
did you include CONFIG += console in your .pro?Laryngeal
@Laryngeal Yeah I did, FYI here's my project source: QT += core QT += network QT -= gui TARGET = qmacid CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp I presume there is some problem in getMacAddress() function.Rhotacism
huh..return interface.hardwareAddress(); so perhaps it returns there without printing anything.Laryngeal
Right, how can I save it to QString? OR do I need to convert it or something?Rhotacism
Look at interface.allAddresses() instead of just the hardwareAddress.Wenzel
@Sosukodo thanks for it, right, how I got to show it on my Console window?? kindly helpRhotacism
Remove your conditional that checks for IsLoopBack.Wenzel
The hardwareAddress is obviously empty for the interface that's passing your conditional so you should look at all interfaces with your own eyes to see what data is available.Wenzel
@Sosukodo Yeah I did, but it displays nothing in the COnsoleRhotacism
Possible duplicate of Obtaining MAC address on windows in QtRecall
W
2

Try this code so show the hardware addresses of each interface:

QString getMacAddress()
{
    QString text;
    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
    {
        text += "Interface:"+interface.hardwareAddress()+"\n";
    }
    return text;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    printf( "%s\n", getMacAddress().toAscii().constData() );
    exit(1);
    return a.exec();
}
Wenzel answered 8/3, 2013 at 8:6 Comment(1)
note: to pass QString as const char * use qPrintable(string)Pierson

© 2022 - 2024 — McMap. All rights reserved.