diff --git a/.gitignore b/.gitignore index 3628172..e627139 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store *build-PolyChat* +*build* # C++ objects and libs *.slo diff --git a/App/bll_polychat.h b/App/bll_polychat.h index 1f7cf57..bdb89be 100644 --- a/App/bll_polychat.h +++ b/App/bll_polychat.h @@ -17,18 +17,37 @@ static QHostAddress getIPAddress() { QHostAddress ipAddress; QList ipAddressesList = QNetworkInterface::allAddresses(); - for (int i = 0; i < ipAddressesList.size(); ++i) + + // 优先寻找以192开头的IPv4地址 + for (const QHostAddress &address : ipAddressesList) { - if (ipAddressesList.at(i) != QHostAddress::LocalHost - && ipAddressesList.at(i).toIPv4Address()) + if (address != QHostAddress::LocalHost && address.toIPv4Address()) { - ipAddress = ipAddressesList.at(i); - break; + QString ipString = address.toString(); + if (ipString.startsWith("192")) + { + ipAddress = address; + break; + } + } + } + + // 如果没有找到以192开头的地址,再考虑其他IPv4地址 + if (ipAddress.isNull()) + { + for (const QHostAddress &address : ipAddressesList) { + if (address != QHostAddress::LocalHost && address.toIPv4Address()) + { + ipAddress = address; + break; + } } } - if (ipAddress.toString().isEmpty()) + // 如果仍然没有找到,返回 localhost IPv4 地址 + if (ipAddress.isNull()) { ipAddress = QHostAddress(QHostAddress::LocalHost); + } return ipAddress; }