-2

I want to verify an IP address in java, how can I do that? The IP Address needs to be in this format: xxx.xxx.xxx.xxx Each octet range must be 0 ~ 255.

Since the IP is verified, the code must show a message telling that the IP is valid or not. If not, the user must type the IP again.

I've done the method to convert an IP string to an array of integers so far...


public static void verify() {
        Scanner input = new Scanner(System.in);     
        System.out.println("IP: (xxx.xxx.xxx.xxx)");
        String ipAddress = input.nextLine();
        int[] arrayIpAddress = Arrays.stream(ipAddress.split("\\.")).mapToInt(Integer::parseInt).toArray();
}

  • Checkout java's [Pattern](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html) and [Matcher](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html) classes for string regex matching. This should help point you in the right direction. – Matt May 31 '19 at 14:54

1 Answers1

2

In your specific scenario, you can add a filter and check the resulting arrays length:

String ipAddress = input.nextLine();
boolean ipValid = Arrays
  .stream(ipAddress.split("\\."))
  .mapToInt(Integer::parseInt)
  .filter(x -> x >= 0 && x <= 255) // remove invalid numbers
  .toArray().length == 4; // if the resulting length is 4, the ip is valid

Note: your approach will fail if Integer.parseInt throws an exception (i.e. if the user enters some letters), and will consider an IP valid even if there is some extra dot (like 192.168.0.1.)

BackSlash
  • 21,927
  • 22
  • 96
  • 136