dnsutils.java

来自「spam source codejasen-0.9jASEN - java An」· Java 代码 · 共 457 行 · 第 1/2 页

JAVA
457
字号
			2. 	Due to some methods of allocating certain styles of IPv6
			  	addresses, it will be common for addresses to contain long strings
			  	of zero bits.  In order to make writing addresses containing zero
			  	bits easier a special syntax is available to compress the zeros.
			  	The use of "::" indicates multiple groups of 16-bits of zeros.
			  	The "::" can only appear once in an address.  The "::" can also be
			  	used to compress the leading and/or trailing zeros in an address.

				For example the following addresses:

				1080:0:0:0:8:800:200C:417A  a unicast address
				FF01:0:0:0:0:0:0:101        a multicast address
				0:0:0:0:0:0:0:1             the loopback address
				0:0:0:0:0:0:0:0             the unspecified addresses

				may be represented as:

					1080::8:800:200C:417A       a unicast address
					FF01::101                   a multicast address
					::1                         the loopback address
					::                          the unspecified addresses

			3. 	An alternative form that is sometimes more convenient when dealing
				with a mixed environment of IPv4 and IPv6 nodes is
				x:x:x:x:x:x:d.d.d.d, where the 'x's are the hexadecimal values of
				the six high-order 16-bit pieces of the address, and the 'd's are
				the decimal values of the four low-order 8-bit pieces of the
				address (standard IPv4 representation).

				Examples:

				0:0:0:0:0:0:13.1.68.3

				0:0:0:0:0:FFFF:129.144.52.38

				or in compressed form:

				::13.1.68.3

				::FFFF:129.144.52.38

     * </pre>
     * @param address
     * @return True if the String passed is a valid IP address, false otherwise
     * @see <a href="http://www.ietf.org/rfc/rfc2373.txt">http://www.ietf.org/rfc/rfc2373.txt</a>
     */
    public static boolean isIPv6Address(String address) {

        
        
        // Define the 3 variant regular expressions:
        String variant1 = "[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}";
        String variant2 = "(?:[0-9A-F]{0,4}:){0,6}:(?:[0-9A-F]{0,4}:){0,5}[0-9A-F]{0,4}";
        String variant3 = "[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}:[0-9A-F]{1,4}";

        Pattern p1 = Pattern.compile(variant1, Pattern.CASE_INSENSITIVE);
        Pattern p2 = Pattern.compile(variant2, Pattern.CASE_INSENSITIVE);
        Pattern p3 = Pattern.compile(variant3, Pattern.CASE_INSENSITIVE);

        if(p1.matcher(address).matches() || p2.matcher(address).matches()) {
            return true;
        }
        else {
            // Test variant 3
            int lastColon = address.lastIndexOf(':');
            String IPv4 = address.substring(lastColon + 1, address.length());
            String IPv6 = address.substring(0, lastColon + 1);
            
            if(IPv6.length() > 2) {
                // Test for compressed address
                if(IPv6.endsWith(":")) {
                    if(IPv6.charAt(IPv6.length() - 2) != ':') {
                        IPv6 = IPv6.substring(0, IPv6.length() -1);
                    }
                }

                if(isIPv4Address(IPv4) && (p3.matcher(IPv6).matches() || p2.matcher(IPv6).matches())) {
                    return true;
                }                
            }
        }

        return false;
    }

    /**
     * Gets the root domain from a fully qualified domain
     * <BR>
     * Eg, gets microsoft.com from a.b.c.microsoft.com
     * @param domain
     * @return
     */
    public static String getRootDomain(String domain) {

        if(domain != null) {
            String suffix = domain.substring (domain.lastIndexOf (".") + 1, domain.length ());

            int segments;

            if (Arrays.binarySearch (TLD, suffix.toLowerCase ()) >= 0)
            {
                // This uses a generic top level domain
                segments = 2;
            }
            else
            {
                // We have a country specific domain
                segments = 3;
            }

            String[] segmentArray = domain.split ("\\.");

            if (segmentArray.length > segments)
            {
                StringBuffer buffer = new StringBuffer ();

                int index = segmentArray.length - segments;

                for (int i = index; i < segmentArray.length; i++)
                {
                    if (i > index)
                    {
                        buffer.append (".");
                    }

                    buffer.append (segmentArray[i]);

                }

                domain = buffer.toString ();
            }

        }

        return domain;
    }

    /**
	 * Inverts the IP address to match the requirements of DNS services.
	 * <br>
	 *
	 * @param originalIPAddress the IP address to invert
	 * @return the inverted form of the passed IP address
	 */
	public static String invertIPAddress(String originalIPAddress) {

		StringTokenizer t = new StringTokenizer(originalIPAddress, ".");
		String inverted = t.nextToken();

		while (t.hasMoreTokens()) {
			inverted = t.nextToken() + "." + inverted;
		}

		return inverted;
	}

    /**
     * Test harness only
     * @param args
     */
    public static void main(String[] args) {
        try
        {
            String[] tests = {
                   "fedc:BA98:7654:3210:FEDC:BA98:7654:3210",
                   "1080:0:0:0:8:800:200C:417A",
                   "FF01:0:0:0:0:0:0:101",
                   "0:0:0:0:0:0:0:1",
                   "0:0:0:0:0:0:0:0",
                   "1080::8:800:200C:417A",
                   "FF01:1080::8:800:200C:417A",
                   "FF01::101",
                   "::1",
                   "::",
                   "0:0:0:0:0:0:13.1.68.3",
                   "0:0:0:0:0:FFFF:129.144.52.38",
                   "::13.1.68.3",
                   "::FFFF:129.144.52.38"};

            for (int i = 0; i < tests.length; i++)
            {
                System.out.println (tests[i] + " -> " + isIPv6Address(tests[i]));
            }

        }
        catch (Exception e)
        {
            e.printStackTrace ();
        }
    }

    /**
     * Gets the valid domain part of a URL.
     * @param host
     * @return Returns null if there is no valid domain
     */
    public static String getValidDomainOnly(String host) {
    	String[] split = null;
    
    	if(!isIPAddress(host)) {
    
    		split = host.split("\\.");
    
    		if(split.length > 2) {
    			if(Arrays.binarySearch(URLParser.URL_WORDS, split[0]) > -1) {
    				host = split[1] + "." + split[2];
    			}
    		}
    		else {
    			// The host is invalid
    			host = null;
    		}
    	}
    
    	return host;
    }
    
    /**
     * Determines if the string passed "appears" to be a valid domain
     * @param str The string to test
     * @return True if the string matches a standard domain sequence.  
     * That is, a sequence of alphanumeric characters delimited by dots.
     * False otherwise
     */
    public static boolean isDomain(String str) {
        return str.matches("[a-z0-9][-a-z0-9]*(\\.[-a-z0-9]+)*\\.[a-z]{2,6}");
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?