1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package examples.cidr;
18
19 import java.util.Arrays;
20 import java.util.Scanner;
21
22 import org.apache.commons.net.util.SubnetUtils;
23 import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
24
25
26
27
28
29
30 public class SubnetUtilsExample {
31
32 public static void main(String[] args) {
33 String subnet = "192.168.0.3/31";
34 SubnetUtils utils = new SubnetUtils(subnet);
35 SubnetInfo info = utils.getInfo();
36
37 System.out.printf("Subnet Information for %s:\n", subnet);
38 System.out.println("--------------------------------------");
39 System.out.printf("IP Address:\t\t\t%s\t[%s]\n", info.getAddress(),
40 Integer.toBinaryString(info.asInteger(info.getAddress())));
41 System.out.printf("Netmask:\t\t\t%s\t[%s]\n", info.getNetmask(),
42 Integer.toBinaryString(info.asInteger(info.getNetmask())));
43 System.out.printf("CIDR Representation:\t\t%s\n\n", info.getCidrSignature());
44
45 System.out.printf("Supplied IP Address:\t\t%s\n\n", info.getAddress());
46
47 System.out.printf("Network Address:\t\t%s\t[%s]\n", info.getNetworkAddress(),
48 Integer.toBinaryString(info.asInteger(info.getNetworkAddress())));
49 System.out.printf("Broadcast Address:\t\t%s\t[%s]\n", info.getBroadcastAddress(),
50 Integer.toBinaryString(info.asInteger(info.getBroadcastAddress())));
51 System.out.printf("Low Address:\t\t\t%s\t[%s]\n", info.getLowAddress(),
52 Integer.toBinaryString(info.asInteger(info.getLowAddress())));
53 System.out.printf("High Address:\t\t\t%s\t[%s]\n", info.getHighAddress(),
54 Integer.toBinaryString(info.asInteger(info.getHighAddress())));
55
56 System.out.printf("Total usable addresses: \t%d\n", Integer.valueOf(info.getAddressCount()));
57 System.out.printf("Address List: %s\n\n", Arrays.toString(info.getAllAddresses()));
58
59 final String prompt ="Enter an IP address (e.g. 192.168.0.10):";
60 System.out.println(prompt);
61 Scanner scanner = new Scanner(System.in);
62 while (scanner.hasNextLine()) {
63 String address = scanner.nextLine();
64 System.out.println("The IP address [" + address + "] is "
65 + (info.isInRange(address) ? "" : "not ")
66 + "within the subnet [" + subnet + "]");
67 System.out.println(prompt);
68 }
69
70 }
71
72 }