1 14 package org.jahia.security.ip; 15 16 import java.util.NoSuchElementException ; 17 import java.util.StringTokenizer ; 18 19 20 113 public class IPNumber implements Cloneable 114 { 115 116 117 protected int mIPNumber = 0; 118 119 120 133 public IPNumber (String ipNumberStr) 134 throws InvalidIPNumberException 135 { 136 mIPNumber = parseIPNUmber (ipNumberStr); 137 } 138 139 140 147 public IPNumber (int number) 148 { 149 mIPNumber = number; 150 } 151 152 153 160 public final int getIPNumber () { 161 return mIPNumber; 162 } 163 164 165 173 public String toString () 174 { 175 StringBuffer result = new StringBuffer (); 176 int temp; 177 178 temp = mIPNumber & 0x000000FF; 179 result.append (temp); 180 result.append ("."); 181 182 temp = (mIPNumber >> 8) & 0x000000FF; 183 result.append (temp); 184 result.append ("."); 185 186 temp = (mIPNumber >> 16) & 0x000000FF; 187 result.append (temp); 188 result.append ("."); 189 190 temp = (mIPNumber >> 24) & 0x000000FF; 191 result.append (temp); 192 193 return result.toString(); 194 } 195 196 197 205 public final boolean isClassA () 206 { 207 return (mIPNumber & 0x00000001) == 0; 208 } 209 210 211 219 public final boolean isClassB () 220 { 221 return (mIPNumber & 0x00000003) == 1; 222 } 223 224 225 233 public final boolean isClassC () 234 { 235 return (mIPNumber & 0x00000007) == 3; 236 } 237 238 253 protected int parseIPNUmber (String ipNumberStr) 254 throws InvalidIPNumberException 255 { 256 int result = 0; 257 258 if (ipNumberStr == null) { 259 throw new InvalidIPNumberException (); 260 } 261 262 StringTokenizer tokenizer = new StringTokenizer (ipNumberStr, "."); 263 try { 264 String tmp = ipNumberStr; 265 266 int offset = 0; 268 for (int i=0; i<3; i++) { 269 270 int index = tmp.indexOf("."); 272 273 if (index != -1) { 276 277 String numberStr = tmp.substring (0, index); 280 int number = Integer.parseInt (numberStr); 281 if ((number < 0) || (number > 255)) { 282 throw new InvalidIPNumberException (ipNumberStr); 283 } 284 285 result += number << offset; 286 offset += 8; 287 tmp = tmp.substring (index+1); 288 } else { 289 throw new InvalidIPNumberException (ipNumberStr); 290 } 291 } 292 293 if (tmp.length() > 0) { 295 int number = Integer.parseInt (tmp); 296 if ((number < 0) || (number > 255)) { 297 throw new InvalidIPNumberException (ipNumberStr); 298 } 299 300 result += number << offset; 301 mIPNumber = result; 302 } else { 303 throw new InvalidIPNumberException (ipNumberStr); 304 } 305 } 306 catch (NoSuchElementException ex) { 307 throw new InvalidIPNumberException (ipNumberStr); 308 } 309 catch (NumberFormatException ex) { 310 throw new InvalidIPNumberException (ipNumberStr); 311 } 312 313 return result; 314 } 315 316 317 328 public boolean equals (Object another) 329 { 330 if (another instanceof IPNumber) { 331 return mIPNumber == ((IPNumber)another).mIPNumber; 332 } 333 return false; 334 } 335 336 343 public Object clone () 344 { 345 return new IPNumber (mIPNumber); 346 } 347 } 348 349 | Popular Tags |