IP.java

 1package eu.siacs.conversations.utils;
 2
 3import java.util.regex.Pattern;
 4
 5public class IP {
 6
 7    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");
 8    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");
 9    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");
10    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");
11    private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
12
13    public static boolean matches(String server) {
14        return server != null && (
15                PATTERN_IPV4.matcher(server).matches()
16                        || PATTERN_IPV6.matcher(server).matches()
17                        || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
18                        || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
19                        || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
20    }
21
22    public static String wrapIPv6(final String host) {
23        if (matches(host)) {
24            return String.format("[%s]", host);
25        } else {
26            return host;
27        }
28    }
29
30}