A string input validator for IPs and domains. : IP Address « Network Protocol « Java






A string input validator for IPs and domains.

     

//Copyright 2007-2009 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at 
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.


//package com.dyuproject.util.validate;

/**
 * A string input validator for IPs and domains.
 * 
 * @author David Yu
 * @created Jan 10, 2009
 */

public final class IPDomainValidator
{
    
    public static final int INVALID = 0;
    public static final int PLAIN = 1;
    public static final int ALPHANUMERIC = 2;
    public static final int HYPHENATED = 3;
    public static final int MIXED = 4;
    public static final int IP = 5;
    
    /**
     * Returns 0 if the char array {@code part} is invalid.
     */
    public static int tokenValidate(char[] part, int start, int len)
    {         
        int digitCount = 0, lastHyphen = -1;
        for(int i=0; i<len; i++)
        {
            char c = part[start++];            
            if(Character.isDigit(c))
                digitCount++;
            else if(!Character.isLetter(c))
            {
                if(c=='-')
                {
                    if(i<len-1)
                    {
                        if(lastHyphen+1==i || lastHyphen-1==i)
                        {
                            // invalid placement of hyphens (succeeding, prefix)                            
                            return INVALID;
                        }
                        lastHyphen = i;
                    }
                    else
                    {
                        // invalid placement of hyphens (suffix)  
                        return INVALID;
                    }
                }
                else
                    return INVALID;
            }
        }
        if(digitCount==len)
            return IP;
        
        if(digitCount==0)
            return lastHyphen==-1 ? PLAIN : HYPHENATED;
        
        return lastHyphen==-1 ? ALPHANUMERIC : MIXED;
    }
    
    /**
     * Returns the index of the char {@code c} from the char array {@code ch}.
     */
    public static int indexOf(char[] ch, char c, int start)
    {
        for(int i=start; i<ch.length; i++)
        {
            if(ch[i]==c)
                return i;
        }
        return -1;
    }
    
    /**
     * Returns the index (starting from the last) of the char {@code c} from the 
     * array of characters {@code ch}.
     */
    public static int lastIndexOf(char[] ch, char c, int start)
    {
        for(int i=start; i-->0;)
        {
            if(ch[i]==c)
                return i;
        }
        return -1;
    }
    
    /**
     * Returns 0 if the string {@code domain} is invalid.
     */
    public static int validate(String domain, int start, int end)
    {
        char[] ch = new char[end-start];
        domain.getChars(start, end, ch, 0);
        return validate(ch);
    }
    
    /**
     * Returns 0 if the string {@code domain} is invalid.
     */
    public static int validate(String domain)
    {
        return validate(domain.toCharArray());
    }
    
    /**
     * Returns 0 if the char array {@code domain} is invalid.
     */
    public static int validate(char[] domain)
    {
        return validate(domain, 0, domain.length);
    }
    
    /**
     * Returns 0 if the char array {@code domain} is invalid.
     */
    public static int validate(char[] domain, int start, int end)
    {        
        boolean mixed = false, hyphenated = false, alphanumeric = false;
        int tokens = 0, digitTokens = 0, extLen = 0;
        for(int i=end; i>0;)
        {
            int idx = lastIndexOf(domain, '.', i-1);
            int l = i-idx-1;
            int check = tokenValidate(domain, idx+1, l);
            i = idx;      
            switch(check)
            {
                case INVALID:
                    return INVALID;
                case PLAIN:
                    if(tokens==0)
                    {
                        if(l==1)
                            return INVALID;
                        
                        extLen = l;
                    }
                    break;
                case ALPHANUMERIC:                    
                    if(tokens==0)
                    {
                        // invalid domain extension (alphanumeric)
                        return INVALID;
                    }
                    alphanumeric = true;                    
                    break;
                case HYPHENATED:
                    if(tokens==0)
                    {
                        // invalid domain extension (alphanumeric)
                        return INVALID;
                    }
                    hyphenated = true;                    
                    break;
                case MIXED:
                    if(tokens==0)
                    {
                        // invalid domain extension (alphanumeric)
                        return INVALID;
                    }
                    mixed = true;                    
                    break;
                case IP:
                    if(tokens==0 && l>3)
                    {
                        // invalid domain extension (max of 3)
                        return INVALID;                    
                    }
                    alphanumeric = true;
                    digitTokens++;                    
                    break;            
            }
            // if exceeds maximum chars for a domain
            if(l>63)
                return INVALID;
            tokens++;
        }
        if(tokens==digitTokens)
            return tokens>4 ? INVALID : IP;
            
        if(extLen==0 || tokens==1)
            return INVALID;
        
        if(mixed)
            return MIXED;
        
        if(hyphenated)
            return HYPHENATED;
        
        return alphanumeric ? ALPHANUMERIC : PLAIN;
    }
    
    /**
     * Checks whether the string {@code domain} is valid.
     */
    public static boolean isValid(String domain)
    {
        return validate(domain)!=INVALID;
    }
    
    /**
     * Checks whether the char array {@code domain} is valid.
     */
    public static boolean isValid(char[] domain)
    {
        return validate(domain)!=INVALID;
    }
    
    /**
     * Checks whether the string {@code domain} is valid.
     */
    public static boolean isValid(String domain, int start, int end)
    {
        return validate(domain, start, end)!=INVALID;
    }
    
    /**
     * Checks whether the char array {@code domain} is valid.
     */
    public static boolean isValid(char[] domain, int start, int end)
    {
        return validate(domain, start, end)!=INVALID;
    }

}
/*

//Copyright 2007-2009 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at 
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.


package com.dyuproject.util.validate;

import junit.framework.TestCase;

// * @author David Yu
// * @created Jan 10, 2009

public class IPDomainValidatorTest extends TestCase
{
    
    public void test1()
    {        
        assertTrue(IPDomainValidator.validate("c.org")==IPDomainValidator.PLAIN);
        assertTrue(IPDomainValidator.validate("c.ph")==IPDomainValidator.PLAIN);        
        assertTrue(IPDomainValidator.validate("123c.com")==IPDomainValidator.ALPHANUMERIC);
        assertTrue(IPDomainValidator.validate("c.museum")==IPDomainValidator.PLAIN);        
        assertTrue(IPDomainValidator.validate("10.com")==IPDomainValidator.ALPHANUMERIC);
        assertTrue(IPDomainValidator.validate("c-b.com")==IPDomainValidator.HYPHENATED);
        
        assertTrue(IPDomainValidator.validate("192.168.1.1")==IPDomainValidator.IP);
        assertTrue(IPDomainValidator.validate("255.255.255.255")==IPDomainValidator.IP);        
        
        String s = "asd1-fc.com";
        assertTrue(IPDomainValidator.validate(s, 1, s.length()-1)==IPDomainValidator.MIXED);
        assertTrue(IPDomainValidator.validate(s.toCharArray(), 1, s.length()-1)==IPDomainValidator.MIXED);
        
        String longDomain = "123456789012345678901234567890123456789012345678901234567890123.com";
        assertTrue(IPDomainValidator.validate(longDomain)==IPDomainValidator.ALPHANUMERIC);
        
        assertTrue(IPDomainValidator.validate("c.o1")==IPDomainValidator.INVALID);        
        assertTrue(IPDomainValidator.validate("c.d")==IPDomainValidator.INVALID);        
        assertTrue(IPDomainValidator.validate("c.d-g")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("c.-dg")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("c.dg-")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("c.d--g")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("c--b.org")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("c-.org")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("-c.org")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("cb-.org")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("-cb.org")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("c_b.org")==IPDomainValidator.INVALID);        
        assertTrue(IPDomainValidator.validate("192.168.1a.1")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("192.1-9.12.1")==IPDomainValidator.INVALID);
        assertTrue(IPDomainValidator.validate("255.255.255.255.1")==IPDomainValidator.INVALID);
        
        assertTrue(IPDomainValidator.validate(longDomain+"4")==IPDomainValidator.INVALID);
        
        assertTrue(IPDomainValidator.validate("localhost")==IPDomainValidator.INVALID);
        
    }

}
*/

   
    
    
    
    
  








Related examples in the same category

1.Get IP
2.Get all IP addresses
3.Convert a hostname to the equivalent IP addressConvert a hostname to the equivalent IP address
4.Getting the Hostname of an IP Address
5.Get canonical host name
6.Getting the IP Address and Hostname of the Local Machine
7.Perform Network Lookup with the InetAddress class
8.Get hostname by a byte array containing the IP address
9.Display multiple IP addresses
10.Looking Up the Address of a HostLooking Up the Address of a Host
11.Retrieve the hostname of an IP Address
12.Retrieve the IP address of a hostname
13.Report By Address
14.Determine the IP address and hostname of the local machine
15.An nslookup clone in Java
16.Looking for Ports: 0 -- 1024
17.Looking for Port: 1024 -- 65536
18.Looking for Port: start from 65535
19.A class that performs some subnet calculations given a network address and a subnet mask.
20.Resolves string ip address and returns host name as a string
21.Resolves hostname and returns ip address as a string
22.Resolves ip address and returns host name as a string
23.This program demonstrates the InetAddress class
24.Check if IP address match pattern
25.Converts IPv4 address in its textual presentation form into its numeric binary form.
26.Convert IPv6 presentation level address to network order binary form.
27.Finds this computer's global IP address
28.Finds a local, non-loopback, IPv4 address
29.Check if the specified address is a valid numeric TCP/IP address
30.Check if the specified address is within the required subnet
31.Check if the specified address is a valid numeric TCP/IP address and return as an integer value
32.Convert a raw IP address array as a String
33.Determine if the given string is a valid IPv4 or IPv6 address.Determine if the given string is a valid IPv4 or IPv6 address.
34.Get Current Environment Network IP