validate ip address using regex

The code snippet below will check if the passed string is a valid IP address or not .
An Internet Protocol address (IP address) is a numerical label assigned to each device participating in a computer network that uses the Internet Protocol for communication. Read more about IP address here. This snippet will validate IP version 4 addresses.

/**
 * validate IP address
 * @param String IP address to verify
 * @return Boolean result
 */
public static Boolean isIP(String input) {
    if (input!= null && !input.isEmpty()) {
        //Regex
        String regex = "^((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)(\\.((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)){3}$";
        //check if input matches the regex
        if (text.matches(regex)) {
            // valid ip
            return true;
        } else {
            // invalid ip
            return false;
        }
    }
    // invalid input
    return false;
}  

 
Dost Muhammad Shah

Dost Muhammad Shah

Dost Muhammad specializing in Embedded Design, Firmware development, PCB designing , testing and prototyping. He enjoys sharing his experience with others .Get in touch with Dost on Twitter or via Contact form

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.