@@ -20,6 +20,7 @@ You should have received a copy of the GNU General Public License
2020using System ;
2121using System . Collections . Generic ;
2222using System . Net ;
23+ using System . Net . Sockets ;
2324
2425namespace TechnitiumLibrary . Net
2526{
@@ -28,6 +29,7 @@ public class NetworkMap<T>
2829 #region variables
2930
3031 readonly List < IpEntry > _ipLookupList ;
32+ AddressFamily _networkFamily = AddressFamily . Unspecified ;
3133 bool _sorted ;
3234
3335 #endregion
@@ -105,6 +107,16 @@ public void Add(NetworkAddress networkAddress, T value)
105107 {
106108 lock ( _ipLookupList )
107109 {
110+ // The first entry decides what kind of network map
111+ // we are creating
112+ if ( _networkFamily == AddressFamily . Unspecified )
113+ {
114+ _networkFamily = networkAddress . AddressFamily ;
115+ }
116+ else if ( _networkFamily != networkAddress . AddressFamily )
117+ {
118+ throw new InvalidOperationException ( "Cannot add network address of different address family to the map." ) ;
119+ }
108120 _ipLookupList . Add ( new IpEntry ( networkAddress . Address , value ) ) ;
109121 _ipLookupList . Add ( new IpEntry ( networkAddress . GetLastAddress ( ) , value ) ) ;
110122
@@ -119,12 +131,19 @@ public bool Remove(string networkAddress)
119131
120132 public bool Remove ( NetworkAddress networkAddress )
121133 {
134+ if ( networkAddress . AddressFamily != _networkFamily )
135+ {
136+ return false ;
137+ }
138+
122139 lock ( _ipLookupList )
123140 {
124141 bool v1 = _ipLookupList . Remove ( new IpEntry ( networkAddress . Address ) ) ;
125142 bool v2 = _ipLookupList . Remove ( new IpEntry ( networkAddress . GetLastAddress ( ) ) ) ;
126143
127144 _sorted = false ;
145+
146+ if ( _ipLookupList . Count == 0 ) _networkFamily = AddressFamily . Unspecified ; // reset internal address family, class may be reused.
128147 return v1 & v2 ;
129148 }
130149 }
@@ -136,6 +155,12 @@ public bool TryGetValue(string address, out T value)
136155
137156 public bool TryGetValue ( IPAddress address , out T value )
138157 {
158+ if ( address . AddressFamily != _networkFamily )
159+ {
160+ value = default ;
161+ return false ;
162+ }
163+
139164 if ( ! _sorted )
140165 {
141166 lock ( _ipLookupList )
@@ -149,7 +174,6 @@ public bool TryGetValue(IPAddress address, out T value)
149174 }
150175
151176 IpEntry findEntry = new IpEntry ( address ) ;
152-
153177 IpEntry floorEntry = GetFloorEntry ( findEntry ) ;
154178 IpEntry ceilingEntry = GetCeilingEntry ( findEntry ) ;
155179
@@ -244,4 +268,4 @@ public T Value
244268 #endregion
245269 }
246270 }
247- }
271+ }
0 commit comments