Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ip;
- import java.util.Scanner;
- /**
- * @author Zigi
- */
- public class IP {
- private static final int IP_PARTS = 4;
- private static final int START = 0;
- private static final int STOP = 1;
- private static final int INPUT_SIZE = 2;
- private static final int PART = 256;
- private static final int PART2 = 256 * 256;
- private static final int PART3 = 256 * 256 * 256;
- private static boolean isValidIP(final String[] parts) {
- if(parts.length != IP_PARTS) {
- System.out.print("Invalid IP structure! ");
- return false;
- }
- for(int i = 0; i < IP_PARTS; i++){
- int partNum = -1;
- try {
- partNum = Integer.parseInt(parts[i]);
- } catch (NumberFormatException e) {
- System.out.print("Non-number entered at position " + (i + 1) + "! ");
- return false;
- }
- if (partNum < 0 || partNum >= PART) {
- System.out.print(
- "The number at position " + (i + 1) +
- " should be in the range [0; 255]! "
- );
- return false;
- }
- }
- return true;
- }
- private static long getNumber(final String[] parts) {
- long number = 0L, exp = 24L;
- for(int position = 0; position < IP_PARTS; position++){
- number += (long)Integer.parseInt(parts[position]) << exp;
- exp -= 8L;
- }
- return number;
- }
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- String parts[][] = new String[INPUT_SIZE][];
- String types[] = {"first", "last"};
- for(int i = 0; i < INPUT_SIZE; i++)
- do {
- System.out.print("Please input " + types[i] + " ip address: ");
- String ip = input.nextLine();
- parts[i] = ip.split("\\.");
- } while (!isValidIP(parts[i]));
- long start = getNumber(parts[START]), stop = getNumber(parts[STOP]) + 1;
- for(long ip = start; ip < stop; ip++) {
- System.out.println(
- ip / PART3 % PART + "." +
- ip / PART2 % PART + "." +
- ip / PART % PART + "." +
- ip % PART
- );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment