Practical No:4
Title:Write a program to demonstrate Sub-netting and find subnet masks
Program:
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
void calculateSubnetMask(int subnetBits) {
unsigned int mask = 0xFFFFFFFF << (32 - subnetBits);
cout << "Subnet Mask: ";
for (int i = 0; i < 4; ++i)
{
cout << ((mask >> (24 - i * 8)) & 0xFF);
if (i < 3) cout << ".";
}
cout << endl;
}
void calculateSubnets(int borrowedBits) {
int numSubnets = pow(2, borrowedBits);
cout << "Number of subnets: " << numSubnets << endl;
}
void calculateHosts(int hostBits) {
int numHosts = pow(2, hostBits) - 2; // Minus 2 for network and broadcast address
cout << "Number of hosts per subnet: " << numHosts << endl;
}
int main() {
int subnetBits, borrowedBits, hostBits;
int classPrefix;
cout << "Enter the number of bits for the network prefix (e.g., 24 for Class C): ";
cin >> classPrefix;
cout << "Enter the number of bits borrowed for subnetting: ";
cin >> borrowedBits;
subnetBits = classPrefix + borrowedBits;
hostBits = 32 - subnetBits;
calculateSubnetMask(subnetBits);
calculateSubnets(borrowedBits);
calculateHosts(hostBits);
return 0;
}
Output:
Enter the number of bits for the network prefix : 255.255.255.224
Enter the number of bits borrowed for subnetting: Subnet Mask: 255.255.255.254
Number of subnets: 1
Number of hosts per subnet: -2
=== Code Execution Successful ===

COMPUTER NETWORKS AND SECURITY PRACTICAL

  • 1.
    Practical No:4 Title:Write aprogram to demonstrate Sub-netting and find subnet masks Program: #include <iostream> #include <cmath> #include <bitset> using namespace std; void calculateSubnetMask(int subnetBits) { unsigned int mask = 0xFFFFFFFF << (32 - subnetBits); cout << "Subnet Mask: "; for (int i = 0; i < 4; ++i) { cout << ((mask >> (24 - i * 8)) & 0xFF); if (i < 3) cout << "."; } cout << endl; } void calculateSubnets(int borrowedBits) { int numSubnets = pow(2, borrowedBits); cout << "Number of subnets: " << numSubnets << endl; } void calculateHosts(int hostBits) { int numHosts = pow(2, hostBits) - 2; // Minus 2 for network and broadcast address cout << "Number of hosts per subnet: " << numHosts << endl; } int main() { int subnetBits, borrowedBits, hostBits; int classPrefix; cout << "Enter the number of bits for the network prefix (e.g., 24 for Class C): "; cin >> classPrefix; cout << "Enter the number of bits borrowed for subnetting: "; cin >> borrowedBits; subnetBits = classPrefix + borrowedBits; hostBits = 32 - subnetBits; calculateSubnetMask(subnetBits); calculateSubnets(borrowedBits); calculateHosts(hostBits); return 0; }
  • 2.
    Output: Enter the numberof bits for the network prefix : 255.255.255.224 Enter the number of bits borrowed for subnetting: Subnet Mask: 255.255.255.254 Number of subnets: 1 Number of hosts per subnet: -2 === Code Execution Successful ===