1 28 29 package com.caucho.util; 30 31 import java.net.InetAddress ; 32 33 36 public class InetNetwork { 37 private long _address; 38 private long _mask; 39 private int _maskIndex; 40 41 47 public InetNetwork(InetAddress inetAddress, int maskIndex) 48 { 49 byte []bytes = inetAddress.getAddress(); 50 51 long address = 0; 52 for (int i = 0; i < bytes.length; i++) 53 address = 256 * address + (bytes[i] & 0xff); 54 55 _address = address; 56 _maskIndex = maskIndex; 57 _mask = -1L << (32 - maskIndex); 58 } 59 60 63 public InetNetwork(long address, int maskIndex) 64 { 65 _address = address; 66 _maskIndex = maskIndex; 67 _mask = -1L << (32 - maskIndex); 68 } 69 70 public static InetNetwork create(String network) 71 { 72 if (network == null) 73 return null; 74 75 int i = 0; 76 int len = network.length(); 77 78 long address = 0; 79 int digits = 0; 80 81 int ch = 0; 82 while (i < len) { 83 if (network.charAt(i) == '/') 84 break; 85 86 int digit = 0; 87 for (; i < len && (ch = network.charAt(i)) >= '0' && ch <= '9'; i++) 88 digit = 10 * digit + ch - '0'; 89 90 address = 256 * address + digit; 91 92 digits++; 93 94 if (i < len && ch == '.') 95 i++; 96 } 97 98 while (digits++ < 4) { 99 address *= 256; 100 } 101 102 103 int mask; 104 if (i < len && network.charAt(i) == '/') { 105 mask = 0; 106 for (i++; i < len && (ch = network.charAt(i)) >= '0' && ch <= '9'; i++) 107 mask = 10 * mask + ch - '0'; 108 } 109 else 110 mask = 32; 111 112 return new InetNetwork(address, mask); 113 } 114 115 118 public boolean isMatch(InetAddress inetAddress) 119 { 120 byte []bytes = inetAddress.getAddress(); 121 122 long address = 0; 123 for (int i = 0; i < bytes.length; i++) 124 address = 256 * address + (bytes[i] & 0xff); 125 126 return (_address & _mask) == (address & _mask); 127 } 128 129 132 public boolean isMatch(byte []bytes) 133 { 134 long address = 0; 135 for (int i = 0; i < bytes.length; i++) 136 address = 256 * address + (bytes[i] & 0xff); 137 138 return (_address & _mask) == (address & _mask); 139 } 140 141 144 public boolean isMatch(long address) 145 { 146 return (_address & _mask) == (address & _mask); 147 } 148 149 152 public String toString() 153 { 154 CharBuffer cb = CharBuffer.allocate(); 155 156 for (int i = 0; i < 4; i++) { 157 if (i != 0) 158 cb.append('.'); 159 160 cb.append((_address >> (3 - i) * 8) & 0xff); 161 } 162 163 cb.append('/'); 164 cb.append(_maskIndex); 165 166 return cb.close(); 167 } 168 } 169 | Popular Tags |