Calculating Subnets

Subnet Calculator: Calculate IP Subnets Easily :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –border-color: #ddd; –card-background: #fff; –shadow: 0 2px 5px rgba(0,0,0,0.1); } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(–background-color); color: var(–text-color); line-height: 1.6; margin: 0; padding: 0; } .container { max-width: 960px; margin: 20px auto; padding: 20px; background-color: var(–card-background); border-radius: 8px; box-shadow: var(–shadow); } header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid var(–border-color); } header h1 { color: var(–primary-color); margin-bottom: 10px; } .calculator-section { margin-bottom: 40px; padding: 30px; background-color: var(–card-background); border-radius: 8px; box-shadow: var(–shadow); } .calculator-section h2 { color: var(–primary-color); text-align: center; margin-bottom: 25px; } .input-group { margin-bottom: 20px; text-align: left; } .input-group label { display: block; margin-bottom: 8px; font-weight: bold; color: var(–primary-color); } .input-group input[type="text"], .input-group input[type="number"], .input-group select { width: calc(100% – 22px); padding: 10px; border: 1px solid var(–border-color); border-radius: 4px; font-size: 1rem; box-sizing: border-box; } .input-group .helper-text { font-size: 0.85em; color: #666; margin-top: 5px; display: block; } .error-message { color: #dc3545; font-size: 0.85em; margin-top: 5px; display: none; /* Hidden by default */ } .button-group { text-align: center; margin-top: 25px; } .button-group button, .button-group input[type="button"] { padding: 10px 20px; margin: 0 10px; border: none; border-radius: 5px; cursor: pointer; font-size: 1rem; transition: background-color 0.3s ease; } .btn-calculate { background-color: var(–primary-color); color: white; } .btn-calculate:hover { background-color: #003366; } .btn-reset { background-color: #6c757d; color: white; } .btn-reset:hover { background-color: #5a6268; } .btn-copy { background-color: var(–success-color); color: white; } .btn-copy:hover { background-color: #218838; } .results-section { margin-top: 30px; padding: 25px; background-color: var(–primary-color); color: white; border-radius: 8px; text-align: center; box-shadow: inset 0 0 10px rgba(0,0,0,0.2); } .results-section h3 { margin-top: 0; margin-bottom: 15px; font-size: 1.4em; } .main-result { font-size: 2.5em; font-weight: bold; margin-bottom: 15px; word-break: break-all; } .intermediate-results div, .formula-explanation { margin-bottom: 10px; font-size: 0.95em; } .formula-explanation { font-style: italic; opacity: 0.9; } table { width: 100%; border-collapse: collapse; margin-top: 20px; margin-bottom: 20px; box-shadow: var(–shadow); } th, td { padding: 12px 15px; text-align: left; border: 1px solid var(–border-color); } thead { background-color: var(–primary-color); color: white; } tbody tr:nth-child(even) { background-color: #f2f2f2; } caption { font-size: 1.1em; font-weight: bold; color: var(–primary-color); margin-bottom: 10px; text-align: left; } canvas { display: block; margin: 20px auto; max-width: 100%; border: 1px solid var(–border-color); border-radius: 4px; } .article-section { margin-top: 40px; padding: 30px; background-color: var(–card-background); border-radius: 8px; box-shadow: var(–shadow); } .article-section h2, .article-section h3 { color: var(–primary-color); margin-bottom: 15px; } .article-section h2 { border-bottom: 2px solid var(–primary-color); padding-bottom: 10px; } .article-section h3 { margin-top: 25px; } .article-section p { margin-bottom: 15px; } .faq-item { margin-bottom: 15px; border-left: 3px solid var(–primary-color); padding-left: 15px; } .faq-item strong { color: var(–primary-color); display: block; margin-bottom: 5px; } .internal-links ul { list-style: none; padding: 0; } .internal-links li { margin-bottom: 10px; } .internal-links a { color: var(–primary-color); text-decoration: none; font-weight: bold; } .internal-links a:hover { text-decoration: underline; } .internal-links span { font-size: 0.9em; color: #555; display: block; margin-top: 3px; } .highlight { background-color: var(–success-color); color: white; padding: 2px 5px; border-radius: 3px; font-weight: bold; } .error-visible { display: block !important; }

Subnet Calculator

Calculate IP subnet details quickly and accurately.

Subnet Calculation Tool

Enter the network address or any IP within the desired network.
Enter the subnet mask in dotted-decimal notation.

Calculation Results

Calculations based on IP address, subnet mask, and binary bitwise operations.
Subnetting Details Table
Metric Value
IP Address N/A
Subnet Mask N/A
Network Address N/A
Broadcast Address N/A
Usable Host Range N/A
Total Addresses in Subnet N/A
Usable Hosts N/A
CIDR Notation N/A
Subnet Address Distribution

What is Subnetting?

Subnetting is a fundamental networking technique that involves dividing a larger IP network into smaller, more manageable subnetworks, or "subnets." This process is crucial for efficient network management, improved performance, and enhanced security. Essentially, subnetting allows administrators to break down a single large block of IP addresses into smaller, distinct groups, each with its own network and broadcast address. This is achieved by borrowing bits from the host portion of an IP address to create a subnet identifier. The primary goal of subnetting is to optimize the use of IP addresses, reduce network traffic by segmenting broadcast domains, and simplify network administration.

Anyone involved in network design, administration, or even advanced IT support will encounter subnetting. This includes network engineers, system administrators, IT managers, and cybersecurity professionals. Understanding subnetting is vital for tasks such as IP address planning, network troubleshooting, and implementing security policies. It's a core concept that underpins how modern networks are structured and function.

A common misconception is that subnetting is only for very large enterprises. In reality, even small to medium-sized businesses benefit significantly from subnetting by segmenting their networks (e.g., separating guest Wi-Fi from the internal corporate network) for security and performance reasons. Another misconception is that it's overly complex; while it involves binary math, the principles are straightforward once understood, and tools like this subnet calculator simplify the practical application.

Who Should Use Subnetting?

  • Network Administrators: For efficient IP address allocation and network segmentation.
  • System Engineers: To understand network topology and troubleshoot connectivity issues.
  • IT Managers: To plan network growth and security strategies.
  • Students and Learners: To grasp core networking concepts.

Common Misconceptions about Subnetting

  • Complexity: Many believe it's too difficult for beginners. While it requires understanding binary, calculators make it accessible.
  • Only for Large Networks: Subnetting is beneficial for networks of all sizes for segmentation and security.
  • Wasted IPs: While each subnet has unusable network and broadcast addresses, efficient subnetting minimizes waste.

Subnetting Formula and Mathematical Explanation

Subnetting involves manipulating IP addresses and subnet masks, which are typically represented in dotted-decimal notation but are fundamentally binary numbers. The core of subnetting lies in understanding how the subnet mask divides an IP address into its network portion and host portion.

The Process:

  1. Binary Conversion: Convert both the IP address and the subnet mask into their 32-bit binary representations.
  2. Network Address Calculation: Perform a bitwise AND operation between the binary IP address and the binary subnet mask. The result is the binary network address.
  3. Broadcast Address Calculation: Take the binary network address, invert the subnet mask (0s become 1s, 1s become 0s), and perform a bitwise OR operation with the inverted mask. Alternatively, set all host bits (the bits corresponding to 0s in the subnet mask) to 1.
  4. Host Address Range: The usable host addresses are all addresses between the network address and the broadcast address, excluding both.
  5. Number of Hosts: The number of usable hosts is 2(number of host bits) – 2. The number of host bits is 32 minus the number of network bits (which is determined by the subnet mask).

Key Formulas:

  • Network Address = IP Address AND Subnet Mask
  • Broadcast Address = Network Address OR (NOT Subnet Mask)
  • Number of Subnets = 2(number of borrowed bits)
  • Number of Hosts per Subnet = 2(number of host bits) – 2

Variable Explanations:

When calculating subnets, we work with IP addresses and subnet masks. The subnet mask is key as it dictates the size and number of subnets.

Subnetting Variables
Variable Meaning Unit Typical Range
IP Address A unique identifier assigned to each device on a network. Dotted-Decimal Notation (e.g., 192.168.1.1) 0.0.0.0 to 255.255.255.255
Subnet Mask Defines the network and host portions of an IP address. Dotted-Decimal Notation (e.g., 255.255.255.0) e.g., 255.0.0.0 to 255.255.255.254 (valid masks)
Network Address The first address in a subnet, identifying the network itself. Dotted-Decimal Notation Derived from IP & Mask
Broadcast Address The last address in a subnet, used to send data to all hosts within that subnet. Dotted-Decimal Notation Derived from IP & Mask
Usable Host Range The range of IP addresses available for assignment to devices within a subnet. Dotted-Decimal Notation (Start – End) Network Address + 1 to Broadcast Address – 1
CIDR Notation Classless Inter-Domain Routing notation, representing the number of network bits. Integer (e.g., /24) /0 to /32
Number of Host Bits The number of bits available for host addresses in the host portion. Count 0 to 30 (for IPv4)
Number of Usable Hosts The total count of IP addresses that can be assigned to devices. Count 0 or more (2host bits – 2)

Practical Examples (Real-World Use Cases)

Example 1: Small Office Network

A small office has been assigned the network address block 192.168.10.0. They want to divide this into four equal subnets for different departments: Sales, Marketing, Engineering, and Admin. They decide to use a subnet mask that allows for this division.

Inputs:

  • IP Address: 192.168.10.0
  • Subnet Mask: 255.255.255.192

Calculation Breakdown:

  • The subnet mask 255.255.255.192 in binary is 11111111.11111111.11111111.11000000.
  • This means there are 26 network bits (24 from the first three octets + 2 from the last octet).
  • The number of borrowed bits is 2 (from the last octet).
  • Number of subnets = 22 = 4 subnets.
  • Number of host bits = 32 – 26 = 6 bits.
  • Number of usable hosts per subnet = 26 – 2 = 64 – 2 = 62 hosts.

Outputs:

  • Network Address: 192.168.10.0
  • Broadcast Address: 192.168.10.63
  • Usable Host Range: 192.168.10.1192.168.10.62
  • CIDR Notation: /26
  • Usable Hosts: 62

Interpretation: This subnet mask effectively divides the original network into 4 subnets, each capable of supporting up to 62 devices. The first subnet starts at 192.168.10.0 and ends at 192.168.10.63. The next subnet would start at 192.168.10.64, and so on.

Example 2: Network Segmentation for Security

A company wants to isolate its guest Wi-Fi network from its internal corporate network for security reasons. They have a block of addresses and need to create a separate subnet for guests.

Inputs:

  • IP Address: 10.0.0.0
  • Subnet Mask: 255.255.255.248

Calculation Breakdown:

  • The subnet mask 255.255.255.248 in binary is 11111111.11111111.11111111.11111000.
  • This means there are 29 network bits.
  • The number of borrowed bits is 5 (from the last octet).
  • Number of subnets = 25 = 32 subnets.
  • Number of host bits = 32 – 29 = 3 bits.
  • Number of usable hosts per subnet = 23 – 2 = 8 – 2 = 6 hosts.

Outputs:

  • Network Address: 10.0.0.0
  • Broadcast Address: 10.0.0.7
  • Usable Host Range: 10.0.0.110.0.0.6
  • CIDR Notation: /29
  • Usable Hosts: 6

Interpretation: This configuration creates a small subnet suitable for a guest network. It provides 6 usable IP addresses, which is enough for a few access points and potentially a small number of guest devices. Crucially, this guest subnet is isolated from the main corporate network, enhancing security.

How to Use This Subnet Calculator

Using this subnet calculator is straightforward. Follow these steps to get your subnet details:

  1. Enter IP Address: In the "IP Address" field, type the IP address of your network or any IP address that falls within the network you want to analyze. For example, you might enter 192.168.1.1 or 192.168.1.0.
  2. Enter Subnet Mask: In the "Subnet Mask" field, enter the corresponding subnet mask in dotted-decimal notation (e.g., 255.255.255.0, 255.255.0.0, or 255.255.255.192).
  3. Click Calculate: Press the "Calculate" button.

How to Read Results:

  • Main Result (e.g., Network Address): This is the primary identifier for your subnet.
  • Intermediate Values:
    • Network Address: The first IP address in the subnet.
    • Broadcast Address: The last IP address in the subnet.
    • Usable Hosts: The total number of IP addresses available for devices within this subnet.
    • CIDR Notation: A shorthand representation of the subnet mask (e.g., /24 for 255.255.255.0).
    • Total Addresses: The total number of IP addresses within the subnet range (including network and broadcast).
  • Table: Provides a structured overview of all calculated metrics.
  • Chart: Visually represents the distribution of addresses within the subnet.

Decision-Making Guidance:

The results help you understand the capacity and boundaries of your network segment. If the "Usable Hosts" count is too low for your needs, you may need to adjust the subnet mask to create larger subnets (fewer subnets, more hosts per subnet). Conversely, if you need to create more subnets, you'll use a mask that borrows more bits from the host portion, resulting in smaller subnets with fewer hosts.

Key Factors That Affect Subnetting Results

While the core calculation is based on the IP address and subnet mask, several underlying factors influence how subnetting is planned and implemented:

  1. Network Size and Growth: The current number of devices and projected growth are primary drivers for determining how many subnets are needed and how large they should be. Planning for future expansion is crucial to avoid re-subnetting later.
  2. Number of Required Subnets: If you need to segment your network for different departments, security zones (e.g., servers, workstations, guests), or physical locations, the number of subnets dictates the subnet mask choice. More subnets require a mask with more network bits.
  3. Number of Hosts per Subnet: Each subnet must accommodate the maximum number of devices expected within that segment. If a subnet needs to support 50 devices, a mask like 255.255.255.192 (/26, 62 hosts) might be suitable, whereas 255.255.255.248 (/29, 6 hosts) would not.
  4. IP Address Availability: The total block of IP addresses allocated to your organization limits the scope of subnetting. Efficient subnetting aims to minimize wasted IP addresses.
  5. Network Performance and Traffic Management: Subnetting helps reduce broadcast domain sizes. A smaller broadcast domain means fewer devices receive broadcast traffic, which can improve overall network performance by reducing unnecessary processing.
  6. Security Policies: Subnetting is a key tool for network security. By placing different types of devices or user groups on separate subnets, administrators can implement more granular firewall rules and access control lists (ACLs) to restrict traffic flow between segments. For instance, isolating the finance department's subnet from the guest Wi-Fi subnet is a common security practice.
  7. Router and Switch Capabilities: The hardware used in the network must support the chosen subnetting scheme and routing protocols. The number of available IP addresses and the complexity of routing tables can be influenced by the subnetting strategy.
  8. Future Technology Adoption: Considerations like the potential adoption of IPv6, cloud services, or IoT devices might influence current IP addressing and subnetting strategies, although IPv4 subnetting remains a core skill.

Frequently Asked Questions (FAQ)

Q: What is the difference between an IP address and a subnet mask?

A: An IP address uniquely identifies a device on a network. A subnet mask defines which part of the IP address represents the network and which part represents the host. It's like a stencil that separates the network ID from the host ID.

Q: Can I use any IP address with any subnet mask?

A: No. Subnet masks must follow specific rules. They consist of a contiguous block of '1's followed by a contiguous block of '0's in binary. This means masks like 255.255.255.192 are valid, but 255.255.0.255 is not.

Q: What is CIDR notation and how does it relate to subnet masks?

A: CIDR (Classless Inter-Domain Routing) notation is a shorthand way to represent a subnet mask. It's written as a forward slash followed by the number of bits in the network portion of the IP address. For example, 255.255.255.0 is equivalent to /24 because there are 24 bits set to '1' in its binary representation.

Q: Why are the first and last IP addresses in a subnet not usable for hosts?

A: The first IP address in a subnet is reserved as the Network Address, which identifies the subnet itself. The last IP address is reserved as the Broadcast Address, used to send data to all devices within that specific subnet. Therefore, these two addresses cannot be assigned to individual devices.

Q: How do I choose the right subnet mask?

A: You choose a subnet mask based on how many subnets you need and how many hosts you need in each subnet. The more bits you borrow from the host portion for subnets, the fewer hosts you can have per subnet, and vice versa. Use our calculator to experiment with different masks.

Q: What happens if I enter an invalid IP address or subnet mask?

A: The calculator will display an error message indicating the invalid input. Ensure you are using standard dotted-decimal notation (e.g., 192.168.1.1 for IP, 255.255.255.0 for mask) and that the mask is valid.

Q: Can this calculator handle IPv6 addresses?

A: This specific calculator is designed for IPv4 subnetting. IPv6 uses a different addressing scheme and subnetting approach (often referred to as prefix length).

Q: What is a "private" IP address range?

A: Private IP address ranges (like 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16) are reserved for use within private networks and are not routable on the public internet. They are commonly used for home and business internal networks and are often subnetted.

Related Tools and Internal Resources

© 2023 Your Company Name. All rights reserved.

function ipToBinary(ip) { var parts = ip.split('.'); var binaryParts = []; for (var i = 0; i < parts.length; i++) { var part = parseInt(parts[i], 10); if (isNaN(part) || part 255) return null; binaryParts.push(part.toString(2).padStart(8, '0')); } return binaryParts.join("); } function binaryToIp(binary) { if (binary.length !== 32) return null; var parts = []; for (var i = 0; i < 32; i += 8) { var part = parseInt(binary.substring(i, i + 8), 2); parts.push(part.toString(10)); } return parts.join('.'); } function calculateSubnet() { var ipAddressInput = document.getElementById('ipAddress').value; var subnetMaskInput = document.getElementById('subnetMask').value; // Clear previous errors document.getElementById('ipAddressError').innerText = ''; document.getElementById('subnetMaskError').innerText = ''; document.getElementById('ipAddressError').classList.remove('error-visible'); document.getElementById('subnetMaskError').classList.remove('error-visible'); var ipBinary = ipToBinary(ipAddressInput); var maskBinary = ipToBinary(subnetMaskInput); if (!ipBinary) { document.getElementById('ipAddressError').innerText = 'Invalid IP Address format.'; document.getElementById('ipAddressError').classList.add('error-visible'); return; } if (!maskBinary) { document.getElementById('subnetMaskError').innerText = 'Invalid Subnet Mask format.'; document.getElementById('subnetMaskError').classList.add('error-visible'); return; } // Validate subnet mask binary pattern (contiguous 1s followed by 0s) var maskPattern = /^1*0*$/; if (!maskPattern.test(maskBinary)) { document.getElementById('subnetMaskError').innerText = 'Subnet mask must have contiguous 1s followed by 0s.'; document.getElementById('subnetMaskError').classList.add('error-visible'); return; } var networkAddressBinary = ''; var broadcastAddressBinary = ''; var cidr = 0; var totalAddresses = 0; var usableHosts = 0; for (var i = 0; i < 32; i++) { var ipBit = ipBinary[i]; var maskBit = maskBinary[i]; if (maskBit === '1') { networkAddressBinary += ipBit; cidr++; } else { networkAddressBinary += '0'; } } var hostBits = 32 – cidr; totalAddresses = Math.pow(2, hostBits); usableHosts = totalAddresses – 2; if (usableHosts < 0) usableHosts = 0; // Handle /31 and /32 cases var invertedMaskBinary = ''; for (var i = 0; i < 32; i++) { invertedMaskBinary += (maskBinary[i] === '0' ? '1' : '0'); } for (var i = 0; i { var octetNum = parseInt(octet, 10); if (index === arr.length – 1) return (octetNum + 1).toString(); return octetNum.toString(); }).join('.'); if (usableHosts === 0) { // For /31 and /32 firstUsableHost = networkAddress; } var lastUsableHost = broadcastAddress.split('.').map((octet, index, arr) => { var octetNum = parseInt(octet, 10); if (index === arr.length – 1) return (octetNum – 1).toString(); return octetNum.toString(); }).join('.'); if (usableHosts === 0) { // For /31 and /32 lastUsableHost = broadcastAddress; } document.getElementById('mainResult').innerText = networkAddress; document.getElementById('networkAddress').innerText = 'Network Address: ' + networkAddress; document.getElementById('broadcastAddress').innerText = 'Broadcast Address: ' + broadcastAddress; document.getElementById('usableHosts').innerText = 'Usable Hosts: ' + usableHosts; document.getElementById('cidrNotation').innerText = 'CIDR Notation: /' + cidr; document.getElementById('totalAddresses').innerText = 'Total Addresses: ' + totalAddresses; document.getElementById('tableIpAddress').innerText = ipAddressInput; document.getElementById('tableSubnetMask').innerText = subnetMaskInput; document.getElementById('tableNetworkAddress').innerText = networkAddress; document.getElementById('tableBroadcastAddress').innerText = broadcastAddress; document.getElementById('tableUsableHostRange').innerText = firstUsableHost + ' – ' + lastUsableHost; document.getElementById('tableTotalAddresses').innerText = totalAddresses; document.getElementById('tableUsableHosts').innerText = usableHosts; document.getElementById('tableCidrNotation').innerText = '/' + cidr; updateChart(cidr, totalAddresses, usableHosts); document.getElementById('resultsSection').style.display = 'block'; } function resetCalculator() { document.getElementById('ipAddress').value = '192.168.1.0'; document.getElementById('subnetMask').value = '255.255.255.0'; document.getElementById('ipAddressError').innerText = "; document.getElementById('subnetMaskError').innerText = "; document.getElementById('ipAddressError').classList.remove('error-visible'); document.getElementById('subnetMaskError').classList.remove('error-visible'); document.getElementById('resultsSection').style.display = 'none'; // Clear table and chart document.getElementById('tableIpAddress').innerText = 'N/A'; document.getElementById('tableSubnetMask').innerText = 'N/A'; document.getElementById('tableNetworkAddress').innerText = 'N/A'; document.getElementById('tableBroadcastAddress').innerText = 'N/A'; document.getElementById('tableUsableHostRange').innerText = 'N/A'; document.getElementById('tableTotalAddresses').innerText = 'N/A'; document.getElementById('tableUsableHosts').innerText = 'N/A'; document.getElementById('tableCidrNotation').innerText = 'N/A'; var canvas = document.getElementById('subnetChart'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); } function copyResults() { var ipAddress = document.getElementById('ipAddress').value; var subnetMask = document.getElementById('subnetMask').value; var mainResult = document.getElementById('mainResult').innerText; var networkAddress = document.getElementById('networkAddress').innerText; var broadcastAddress = document.getElementById('broadcastAddress').innerText; var usableHosts = document.getElementById('usableHosts').innerText; var cidrNotation = document.getElementById('cidrNotation').innerText; var totalAddresses = document.getElementById('totalAddresses').innerText; var resultsText = "Subnet Calculation Results:\n\n"; resultsText += "IP Address: " + ipAddress + "\n"; resultsText += "Subnet Mask: " + subnetMask + "\n"; resultsText += "—————————-\n"; resultsText += mainResult + "\n"; resultsText += networkAddress + "\n"; resultsText += broadcastAddress + "\n"; resultsText += usableHosts + "\n"; resultsText += cidrNotation + "\n"; resultsText += totalAddresses + "\n"; if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(resultsText).then(function() { alert('Results copied to clipboard!'); }).catch(function(err) { console.error('Failed to copy: ', err); fallbackCopyTextToClipboard(resultsText); }); } else { fallbackCopyTextToClipboard(resultsText); } } function fallbackCopyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.value = text; textArea.style.position = "fixed"; textArea.style.top = "0"; textArea.style.left = "0"; textArea.style.width = "2em"; textArea.style.height = "2em"; textArea.style.padding = "0"; textArea.style.border = "none"; textArea.style.outline = "none"; textArea.style.boxShadow = "none"; textArea.style.background = "transparent"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Fallback: Copying text command was ' + msg); alert('Results copied to clipboard!'); } catch (err) { console.error('Fallback: Oops, unable to copy', err); alert('Failed to copy results. Please copy manually.'); } document.body.removeChild(textArea); } function updateChart(cidr, totalAddresses, usableHosts) { var canvas = document.getElementById('subnetChart'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear previous chart var chartWidth = canvas.width; var chartHeight = canvas.height; var padding = 40; var availableWidth = chartWidth – 2 * padding; var availableHeight = chartHeight – 2 * padding; // Data var reservedAddresses = 2; if (totalAddresses <= 2) reservedAddresses = totalAddresses; // Handle /31 and /32 var actualUsableHosts = totalAddresses – reservedAddresses; if (actualUsableHosts < 0) actualUsableHosts = 0; var data = { labels: ['Reserved (Network/Broadcast)', 'Usable Hosts'], datasets: [{ label: 'Address Distribution', data: [reservedAddresses, actualUsableHosts], backgroundColor: [ 'rgba(220, 53, 69, 0.7)', // Red for reserved 'rgba(40, 167, 69, 0.7)' // Green for usable ], borderColor: [ 'rgba(220, 53, 69, 1)', 'rgba(40, 167, 69, 1)' ], borderWidth: 1 }] }; // Draw Pie Chart var total = data.datasets[0].data.reduce(function(sum, value) { return sum + value; }, 0); var startAngle = -0.5 * Math.PI; // Start at top var currentAngle = startAngle; data.datasets[0].data.forEach(function(value, i) { var sliceAngle = (value / total) * 2 * Math.PI; ctx.beginPath(); ctx.moveTo(padding + availableWidth / 2, padding + availableHeight / 2); // Center ctx.arc(padding + availableWidth / 2, padding + availableHeight / 2, Math.min(availableWidth, availableHeight) / 2, currentAngle, currentAngle + sliceAngle); ctx.closePath(); ctx.fillStyle = data.datasets[0].backgroundColor[i]; ctx.fill(); ctx.strokeStyle = data.datasets[0].borderColor[i]; ctx.stroke(); // Add labels ctx.fillStyle = '#000'; // Black text ctx.font = '14px Arial'; var midAngle = currentAngle + sliceAngle / 2; var labelRadius = Math.min(availableWidth, availableHeight) / 2 + 20; var labelX = padding + availableWidth / 2 + Math.cos(midAngle) * labelRadius; var labelY = padding + availableHeight / 2 + Math.sin(midAngle) * labelRadius; var labelText = data.labels[i] + ': ' + value; ctx.textAlign = 'center'; ctx.fillText(labelText, labelX, labelY); currentAngle += sliceAngle; }); // Add Title/Caption ctx.fillStyle = '#004a99'; ctx.font = 'bold 16px Arial'; ctx.textAlign = 'center'; ctx.fillText('Address Distribution for /' + cidr + ' Subnet', chartWidth / 2, padding / 2); } // Initial calculation on load if default values are present document.addEventListener('DOMContentLoaded', function() { calculateSubnet(); });

Leave a Comment