Qt提供了类QNetworkInterface用于获取IP和MAC地址,需在pro文件中加入
QT += network
具体代码如下:
#include "widget.h" #include "ui_widget.h" #include <QNetworkInterface> #include<QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QString ipAddr; QList<QNetworkInterface> network = QNetworkInterface::allInterfaces(); foreach (QNetworkInterface i, network) { QString netName = i.humanReadableName(); qDebug()<<netName; if(netName == tr("无线网络连接")) { qDebug()<<i.hardwareAddress(); QList<QNetworkAddressEntry> ipAll = i.addressEntries(); foreach (QNetworkAddressEntry ip, ipAll) { if(ip.ip().protocol()==QAbstractSocket::IPv4Protocol) ipAddr = ip.ip().toString(); } } } qDebug()<<"ipAddr = "<<ipAddr; } Widget::~Widget() { delete ui; }
结果为:
"无线网络连接" "40:F0:2F:1B:05:F9" "本地连接" "VMware Network Adapter VMnet1" "VMware Network Adapter VMnet8" "Loopback Pseudo-Interface 1" "isatap.localdomain" "isatap.{D159E0D6-D661-474C-9552-5D3D9944EA83}" "isatap.{EE78D248-2FB3-4BFC-8716-312559A7D9A1}" "Teredo Tunneling Pseudo-Interface" ipAddr = "192.168.43.122"