-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkAddressCalculator.java
More file actions
54 lines (44 loc) · 2.11 KB
/
NetworkAddressCalculator.java
File metadata and controls
54 lines (44 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.Scanner;
public class NetworkAddressCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get user input
System.out.print("Enter IP address : ");
String ipAddress = scanner.nextLine();
System.out.print("Enter prefix length : ");
int prefixLength = scanner.nextInt();
scanner.close();
// Compute Network Address, Subnet Mask, and Total Hosts
String subnetMask = calculateSubnetMask(prefixLength);
String networkAddress = calculateNetworkAddress(ipAddress, subnetMask);
int totalHosts = (int) Math.pow(2, 32 - prefixLength) - 2; // -2 for Network & Broadcast
// Display results
System.out.println("Network Address: " + networkAddress);
System.out.println("Subnet Mask: " + subnetMask);
System.out.println("Total Number of Hosts: " + totalHosts);
}
public static String calculateSubnetMask(int prefix) {
int mask = 0xFFFFFFFF << (32 - prefix);
return ((mask >> 24) & 0xFF) + "." +
((mask >> 16) & 0xFF) + "." +
((mask >> 8) & 0xFF) + "." +
(mask & 0xFF);
}
public static String calculateNetworkAddress(String ip, String subnetMask) {
String[] ipParts = ip.split("\\.");
String[] maskParts = subnetMask.split("\\.");
int ipInt = (Integer.parseInt(ipParts[0]) << 24) |
(Integer.parseInt(ipParts[1]) << 16) |
(Integer.parseInt(ipParts[2]) << 8) |
Integer.parseInt(ipParts[3]);
int maskInt = (Integer.parseInt(maskParts[0]) << 24) |
(Integer.parseInt(maskParts[1]) << 16) |
(Integer.parseInt(maskParts[2]) << 8) |
Integer.parseInt(maskParts[3]);
int networkInt = ipInt & maskInt;
return ((networkInt >> 24) & 0xFF) + "." +
((networkInt >> 16) & 0xFF) + "." +
((networkInt >> 8) & 0xFF) + "." +
(networkInt & 0xFF);
}
}