Skip to content

Commit

Permalink
优化 多网卡下优先广播 192 开头 IP
Browse files Browse the repository at this point in the history
  • Loading branch information
nekosilverfox committed Apr 13, 2024
1 parent f18b1a6 commit f435441
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.DS_Store
*build-PolyChat*
*build*

# C++ objects and libs
*.slo
Expand Down
31 changes: 25 additions & 6 deletions App/bll_polychat.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,37 @@ static QHostAddress getIPAddress()
{
QHostAddress ipAddress;
QList<QHostAddress> 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;
}
Expand Down

0 comments on commit f435441

Please sign in to comment.