1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | public int parseNumericAddress(String ipaddr) { // Check if the string is valid if (ipaddr == null || ipaddr.length() < 7 || ipaddr.length() > 15) return 0; // Check the address string, should be n.n.n.n format StringTokenizer token = new StringTokenizer(ipaddr, "."); if (token.countTokens() != 4) return 0; int ipInt = 0; while (token.hasMoreTokens()) { // Get the current token and convert to an integer value String ipNum = token.nextToken(); try { // Validate the current address part int ipVal = Integer.valueOf(ipNum).intValue(); if (ipVal < 0 || ipVal > 255) return 0; // Add to the integer address ipInt = (ipInt << 8) + ipVal; } catch (NumberFormatException ex) { return 0; } } // Return the integer address return ipInt; } |
沒有留言:
張貼留言