Qt 获取本机的IP地址和Mac地址


#include #include



获取IP地址


QString getHostIpAddress() {

QString strIpAddress;

QList list = QNetworkInterface::allAddresses();

foreach (QHostAddress address, list)

{

if(address.protocol() == QAbstractSocket::IPv4Protocol)

{

//IPv4地址

if (address.toString().contains("127.0."))

{

continue;

}

strIpAddress = address.toString();

}

}

if (strIpAddress == "127.0.0.1")

{

qDebug() << "获取IP失败!";

return "";

}

return strIpAddress;

}




获取Mac地址
QString getHostMacAddress() { QList nets = QNetworkInterface::allInterfaces(); // 获取所有网络接口列表 int nCnt = nets.count(); QString strMacAddr = ""; for(int i = 0; i < nCnt; i ++) { // 如果此网络接口被激活并且正在运行并且不是回环地址,则就是我们需要找的Mac地址 if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack)) { strMacAddr = nets[i].hardwareAddress(); break; } } return strMacAddr; }




【Qt 获取本机的IP地址和Mac地址】

    推荐阅读