Skip to content

Commit be21eec

Browse files
Merge pull request #164 from NekoSilverFox/MengJianing
优化 多网卡下优先广播 192 开头 IP
2 parents 7587191 + f435441 commit be21eec

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
.DS_Store
22
*build-PolyChat*
3+
*build*
34

45
# C++ objects and libs
56
*.slo

App/bll_polychat.h

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,37 @@ static QHostAddress getIPAddress()
1717
{
1818
QHostAddress ipAddress;
1919
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
20-
for (int i = 0; i < ipAddressesList.size(); ++i)
20+
21+
// 优先寻找以192开头的IPv4地址
22+
for (const QHostAddress &address : ipAddressesList)
2123
{
22-
if (ipAddressesList.at(i) != QHostAddress::LocalHost
23-
&& ipAddressesList.at(i).toIPv4Address())
24+
if (address != QHostAddress::LocalHost && address.toIPv4Address())
2425
{
25-
ipAddress = ipAddressesList.at(i);
26-
break;
26+
QString ipString = address.toString();
27+
if (ipString.startsWith("192"))
28+
{
29+
ipAddress = address;
30+
break;
31+
}
32+
}
33+
}
34+
35+
// 如果没有找到以192开头的地址,再考虑其他IPv4地址
36+
if (ipAddress.isNull())
37+
{
38+
for (const QHostAddress &address : ipAddressesList) {
39+
if (address != QHostAddress::LocalHost && address.toIPv4Address())
40+
{
41+
ipAddress = address;
42+
break;
43+
}
2744
}
2845
}
2946

30-
if (ipAddress.toString().isEmpty())
47+
// 如果仍然没有找到,返回 localhost IPv4 地址
48+
if (ipAddress.isNull()) {
3149
ipAddress = QHostAddress(QHostAddress::LocalHost);
50+
}
3251

3352
return ipAddress;
3453
}

0 commit comments

Comments
 (0)