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...

highlander141
  • 1,683
  • 3
  • 23
  • 48
  • did you include `CONFIG += console` in your .pro? – zzk Mar 08 '13 at 06:13
  • @zzk 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. – highlander141 Mar 08 '13 at 06:16
  • huh..`return interface.hardwareAddress();` so perhaps it returns there without printing anything. – zzk Mar 08 '13 at 06:25
  • Right, how can I save it to QString? OR do I need to convert it or something? – highlander141 Mar 08 '13 at 06:34
  • Look at interface.allAddresses() instead of just the hardwareAddress. –  Mar 08 '13 at 06:34
  • @Sosukodo thanks for it, right, how I got to show it on my Console window?? kindly help – highlander141 Mar 08 '13 at 06:38
  • Remove your conditional that checks for IsLoopBack. –  Mar 08 '13 at 07:49
  • 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. –  Mar 08 '13 at 07:52
  • @Sosukodo Yeah I did, but it displays nothing in the COnsole – highlander141 Mar 08 '13 at 07:55
  • Possible duplicate of [Obtaining MAC address on windows in Qt](https://stackoverflow.com/questions/7609953/obtaining-mac-address-on-windows-in-qt) – iammilind Jan 08 '19 at 04:19

1 Answers1

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();
}