IP Address Validation

  • + 2 comments

    JAVA

    import java.io.*;
    import java.util.*;
    import java.util.regex.*;
    public class Solution {
    
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    
        String range255="(\\d{1,2}|[01][0-9][0-9]|[2][0-5][0-5])\\.";
        Pattern ipv4=Pattern.compile("^"+range255+range255+range255+range255);
        String rangeHexa="(\\.{4}|((\\.{3})?)[0-9_a-fA-F]|((\\.{2})?)[0-9_a-fA-F]{2}|((\\.?)[0-9_A-Fa-f]{3})|([0-9_a-fA-F]{4})):";
        Pattern ipv6=Pattern.compile("^"+rangeHexa+rangeHexa+rangeHexa+
        rangeHexa+rangeHexa+rangeHexa+rangeHexa+rangeHexa);
        Scanner sc= new Scanner(System.in);
        String line="";
        sc.nextLine();
        while(sc.hasNext()){
           line=sc.nextLine();
            if(ipv4.matcher(line+".$").find()){
                System.out.println("IPv4");
            }
            else if(ipv6.matcher(line+":$").find()){
                System.out.println("IPv6");
            }
            else
                System.out.println("Neither");
        }
    }
    }