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        assert matcher.groupCount() == 4;
033
034        for (int i = 1; i <= 4; i++) {
035            String ipSegment = matcher.group(i);
036            int ipSegmentInt;
037            try {
038                ipSegmentInt = Integer.valueOf(ipSegment);
039            } catch (NumberFormatException e) {
040                throw new AssertionError(e);
041            }
042            if (ipSegmentInt > 255) {
043                return false;
044            }
045        }
046        return true;
047    }
048
049    public static boolean isIPv6LiteralAddress(final String string) {
050        final String[] octets = string.split(":");
051        if (octets.length != 8) {
052            return false;
053        }
054        // TODO handle compressed zeros and validate octets
055        return true;
056    }
057
058    public static boolean isIpAddress(String string) {
059        return isIPv4LiteralAddress(string) || isIPv6LiteralAddress(string);
060    }
061}