1
+ using System ;
1
2
using System . Collections . Generic ;
3
+ using System . Collections . ObjectModel ;
2
4
using System . Linq ;
3
5
using System . Net ;
4
6
using System . Net . NetworkInformation ;
@@ -13,6 +15,16 @@ namespace NitroxModel.Helper
13
15
{
14
16
public static class NetHelper
15
17
{
18
+ private static readonly string [ ] privateNetworks =
19
+ {
20
+ "10.0.0.0/8" ,
21
+ "127.0.0.0/8" ,
22
+ "172.16.0.0/12" ,
23
+ "192.0.0.0/24 " ,
24
+ "192.168.0.0/16" ,
25
+ "198.18.0.0/15" ,
26
+ } ;
27
+
16
28
private static IPAddress wanIpCache ;
17
29
private static IPAddress lanIpCache ;
18
30
private static readonly object wanIpLock = new ( ) ;
@@ -69,7 +81,7 @@ public static async Task<IPAddress> GetWanIpAsync()
69
81
70
82
IPAddress ip = await NatHelper . GetExternalIpAsync ( ) ;
71
83
#if RELEASE
72
- if ( ip == null )
84
+ if ( ip == null || ip . IsPrivate ( ) )
73
85
{
74
86
Regex regex = new ( @"(?:[0-2]??[0-9]{1,2}\.){3}[0-2]??[0-9]+" , RegexOptions . Compiled ) ;
75
87
string [ ] sites =
@@ -124,5 +136,31 @@ public static IPAddress GetHamachiIp()
124
136
}
125
137
return null ;
126
138
}
139
+
140
+ /// <summary>
141
+ /// Returns true if the given IP address is reserved for private networks.
142
+ /// </summary>
143
+ public static bool IsPrivate ( this IPAddress address )
144
+ {
145
+ static bool IsInRange ( IPAddress ipAddress , string mask )
146
+ {
147
+ string [ ] parts = mask . Split ( '/' ) ;
148
+
149
+ int ipNum = BitConverter . ToInt32 ( ipAddress . GetAddressBytes ( ) , 0 ) ;
150
+ int cidrAddress = BitConverter . ToInt32 ( IPAddress . Parse ( parts [ 0 ] ) . GetAddressBytes ( ) , 0 ) ;
151
+ int cidrMask = IPAddress . HostToNetworkOrder ( - 1 << ( 32 - int . Parse ( parts [ 1 ] ) ) ) ;
152
+
153
+ return ( ipNum & cidrMask ) == ( cidrAddress & cidrMask ) ;
154
+ }
155
+
156
+ foreach ( string privateSubnet in privateNetworks )
157
+ {
158
+ if ( IsInRange ( address , privateSubnet ) )
159
+ {
160
+ return true ;
161
+ }
162
+ }
163
+ return false ;
164
+ }
127
165
}
128
166
}
0 commit comments