Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Hostgator 1 Penny

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


7,621 questions

10,674 answers

573 users

How to check if a string is valid IPv4 (IP) address in Java

2 Answers

0 votes
public class MyClass {

    static boolean is_valid_IPv4(String s) {
        String ipv4form = "\\b(?:(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}" +
                          "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b";
        return s.matches(ipv4form);
    }
 
    public static void main(String args[]) {
        
         if (is_valid_IPv4("127.0.0.1")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("172.16.251.1")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("85.98.555.1")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("255.255.255.a")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("255.255.255.0.0")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
    }
}

/*
run:

Valid

Valid

Not valid

Not valid

Not valid

*/

 




answered May 15 by avibootz
0 votes
public class MyClass {

    static boolean is_valid_IPv4(String s) {
        String[] arr = s.split("\\.");
        if (arr.length != 4)
            return false;
        for (String ip_part: arr) {
            if (!ip_part.matches("\\d+"))
                return false;
            else if (Integer.parseInt(ip_part) < 0 || Integer.parseInt(ip_part) > 255)
                return false;
        }
        return true;
    }
 
    public static void main(String args[]) {
        
         if (is_valid_IPv4("127.0.0.1")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("172.16.251.1")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("85.98.555.1")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("255.255.255.a")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
         if (is_valid_IPv4("255.255.255.0.0")) System.out.println("Valid\n"); else System.out.println("Not valid\n");
    }
}

/*
run:

Valid

Valid

Not valid

Not valid

Not valid

*/

 




answered May 15 by avibootz
...