IP.java

 1package eu.siacs.conversations.utils;
 2
 3import com.google.common.net.InetAddresses;
 4
 5import java.util.regex.Pattern;
 6
 7public class IP {
 8
 9    private static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
10    private static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
11    private static final Pattern PATTERN_IPV6_6HEX4DEC = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
12    private static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z");
13    private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
14
15    public static boolean matches(String server) {
16        return server != null && (
17                PATTERN_IPV4.matcher(server).matches()
18                        || PATTERN_IPV6.matcher(server).matches()
19                        || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
20                        || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
21                        || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
22    }
23
24    public static String wrapIPv6(final String host) {
25        if (matches(host)) {
26            return String.format("[%s]", host);
27        } else {
28            return host;
29        }
30    }
31
32    public static String unwrapIPv6(final String host) {
33        if (host.length() > 2 && host.charAt(0) == '[' && host.charAt(host.length() - 1) == ']') {
34            final String ip = host.substring(1,host.length() -1);
35            if (InetAddresses.isInetAddress(ip)) {
36                return ip;
37            }
38        }
39        return host;
40    }
41
42}