001/** 002 * 003 * Copyright 2015 Florian Schmaus 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smack.util; 018 019import java.util.regex.Matcher; 020import java.util.regex.Pattern; 021 022public class IpAddressUtil { 023 024 private static final Pattern IPV4_PATTERN = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"); 025 026 public static boolean isIPv4LiteralAddress(String string) { 027 Matcher matcher = IPV4_PATTERN.matcher(string); 028 if (!matcher.matches()) { 029 return false; 030 } 031 032 for (int i = 0; i < 3; i++) { 033 String ipSegment = matcher.group(i); 034 int ipSegmentInt; 035 try { 036 ipSegmentInt = Integer.valueOf(ipSegment); 037 } catch (NumberFormatException e) { 038 throw new AssertionError(e); 039 } 040 if (ipSegmentInt > 255) { 041 return false; 042 } 043 } 044 return true; 045 } 046 047 public static boolean isIPv6LiteralAddress(final String string) { 048 final String[] octets = string.split(":"); 049 if (octets.length != 8) { 050 return false; 051 } 052 // TODO handle compressed zeros and validate octets 053 return true; 054 } 055 056 public static boolean isIpAddress(String string) { 057 return isIPv4LiteralAddress(string) || isIPv6LiteralAddress(string); 058 } 059}