1 17 package org.alfresco.filesys.util; 18 19 import java.net.InetAddress ; 20 import java.util.StringTokenizer ; 21 22 25 public class IPAddress 26 { 27 28 34 public final static boolean isNumericAddress(String ipaddr) 35 { 36 37 39 if (ipaddr == null || ipaddr.length() < 7 || ipaddr.length() > 15) 40 return false; 41 42 44 StringTokenizer token = new StringTokenizer (ipaddr, "."); 45 if (token.countTokens() != 4) 46 return false; 47 48 while (token.hasMoreTokens()) 49 { 50 51 53 String ipNum = token.nextToken(); 54 55 try 56 { 57 int ipVal = Integer.valueOf(ipNum).intValue(); 58 if (ipVal < 0 || ipVal > 255) 59 return false; 60 } 61 catch (NumberFormatException ex) 62 { 63 return false; 64 } 65 } 66 67 69 return true; 70 } 71 72 79 public final static int parseNumericAddress(String ipaddr) 80 { 81 82 84 if (ipaddr == null || ipaddr.length() < 7 || ipaddr.length() > 15) 85 return 0; 86 87 89 StringTokenizer token = new StringTokenizer (ipaddr, "."); 90 if (token.countTokens() != 4) 91 return 0; 92 93 int ipInt = 0; 94 95 while (token.hasMoreTokens()) 96 { 97 98 100 String ipNum = token.nextToken(); 101 102 try 103 { 104 105 107 int ipVal = Integer.valueOf(ipNum).intValue(); 108 if (ipVal < 0 || ipVal > 255) 109 return 0; 110 111 113 ipInt = (ipInt << 8) + ipVal; 114 } 115 catch (NumberFormatException ex) 116 { 117 return 0; 118 } 119 } 120 121 123 return ipInt; 124 } 125 126 132 public final static int asInteger(InetAddress ipaddr) 133 { 134 135 137 byte[] addrBytes = ipaddr.getAddress(); 138 139 141 return DataPacker.getInt(addrBytes, 0); 142 } 143 144 152 public final static boolean isInSubnet(String ipaddr, String subnet, String mask) 153 { 154 155 157 int ipaddrInt = parseNumericAddress(ipaddr); 158 if (ipaddrInt == 0) 159 return false; 160 161 int subnetInt = parseNumericAddress(subnet); 162 if (subnetInt == 0) 163 return false; 164 165 int maskInt = parseNumericAddress(mask); 166 if (maskInt == 0) 167 return false; 168 169 171 if ((ipaddrInt & maskInt) == subnetInt) 172 return true; 173 return false; 174 } 175 176 182 public final static String asString(byte[] ipaddr) 183 { 184 185 187 if (ipaddr == null || ipaddr.length != 4) 188 return null; 189 190 192 StringBuffer str = new StringBuffer (); 193 194 str.append((int) (ipaddr[0] & 0xFF)); 195 str.append("."); 196 str.append((int) (ipaddr[1] & 0xFF)); 197 str.append("."); 198 str.append((int) (ipaddr[2] & 0xFF)); 199 str.append("."); 200 str.append((int) (ipaddr[3] & 0xFF)); 201 202 204 return str.toString(); 205 } 206 } 207 | Popular Tags |