fix Broadcast-Adresse and last ip-adresse

This commit is contained in:
2025-03-29 18:16:41 +01:00
parent 6dfc86ce48
commit 0da70547aa

View File

@@ -2,7 +2,6 @@
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('subnet-form'); const form = document.getElementById('subnet-form');
if (form) { if (form) {
console.log("Attaching submit listener to form:", form);
form.addEventListener('submit', handleSubnetCalculation); form.addEventListener('submit', handleSubnetCalculation);
} else { } else {
console.error("Subnetz-Formular (ID: subnet-form) nicht gefunden!"); console.error("Subnetz-Formular (ID: subnet-form) nicht gefunden!");
@@ -11,7 +10,6 @@ document.addEventListener('DOMContentLoaded', () => {
// Funktion zur Behandlung der Subnetzberechnung bei Formularübermittlung // Funktion zur Behandlung der Subnetzberechnung bei Formularübermittlung
function handleSubnetCalculation(event) { function handleSubnetCalculation(event) {
console.log("handleSubnetCalculation called"); // Protokoll: Start
event.preventDefault(); // Verhindert das Neuladen der Seite event.preventDefault(); // Verhindert das Neuladen der Seite
clearResults(); // Ergebnisse zuerst löschen/verstecken clearResults(); // Ergebnisse zuerst löschen/verstecken
@@ -19,88 +17,69 @@ function handleSubnetCalculation(event) {
const cidrInput = document.getElementById('cidr').value.trim(); const cidrInput = document.getElementById('cidr').value.trim();
const resultsDiv = document.getElementById('results'); // Ergebnis-Div holen const resultsDiv = document.getElementById('results'); // Ergebnis-Div holen
console.log(`Inputs: IP=${ipAddressInput}, CIDR/Mask=${cidrInput}`); // Protokoll: Eingaben
// Einfache Validierung // Einfache Validierung
if (!isValidIP(ipAddressInput)) { if (!isValidIP(ipAddressInput)) {
console.error("Invalid IP address:", ipAddressInput); // Protokoll: Fehler
alert("Bitte geben Sie eine gültige IPv4-Adresse ein."); alert("Bitte geben Sie eine gültige IPv4-Adresse ein.");
return; return;
} }
console.log("IP is valid"); // Protokoll: Erfolg
let cidr; let cidr;
let subnetMask; let subnetMask;
// Prüfen, ob CIDR oder Subnetzmaske eingegeben wurde // Prüfen, ob CIDR oder Subnetzmaske eingegeben wurde
if (cidrInput.includes('.')) { // Annahme: Subnetzmaske im Format xxx.xxx.xxx.xxx if (cidrInput.includes('.')) { // Annahme: Subnetzmaske im Format xxx.xxx.xxx.xxx
console.log("Input detected as subnet mask"); // Protokoll: Pfad
if (!isValidIP(cidrInput)) { if (!isValidIP(cidrInput)) {
console.error("Invalid subnet mask:", cidrInput); // Protokoll: Fehler
alert("Bitte geben Sie eine gültige Subnetzmaske ein."); alert("Bitte geben Sie eine gültige Subnetzmaske ein.");
return; return;
} }
subnetMask = cidrInput; subnetMask = cidrInput;
cidr = maskToCidr(subnetMask); cidr = maskToCidr(subnetMask);
if (cidr === null) { if (cidr === null) {
console.error("maskToCidr returned null for mask:", subnetMask); // Protokoll: Fehler
alert("Ungültige Subnetzmaske. Sie muss aus einer kontinuierlichen Folge von Einsen gefolgt von Nullen bestehen (z.B. 255.255.255.0, nicht 255.255.0.255)."); alert("Ungültige Subnetzmaske. Sie muss aus einer kontinuierlichen Folge von Einsen gefolgt von Nullen bestehen (z.B. 255.255.255.0, nicht 255.255.0.255).");
return; return;
} }
console.log(`Mask converted to CIDR: ${cidr}`); // Protokoll: Erfolg
} else { // Annahme: CIDR-Notation } else { // Annahme: CIDR-Notation
console.log("Input detected as CIDR notation"); // Protokoll: Pfad
cidr = parseInt(cidrInput, 10); cidr = parseInt(cidrInput, 10);
if (isNaN(cidr) || cidr < 0 || cidr > 32) { if (isNaN(cidr) || cidr < 0 || cidr > 32) {
console.error("Invalid CIDR value:", cidrInput); // Protokoll: Fehler
alert("Bitte geben Sie einen gültigen CIDR-Wert (0-32) ein."); alert("Bitte geben Sie einen gültigen CIDR-Wert (0-32) ein.");
return; return;
} }
subnetMask = cidrToMask(cidr); subnetMask = cidrToMask(cidr);
if (subnetMask === null) { if (subnetMask === null) {
console.error("cidrToMask returned null for CIDR:", cidr); // Protokoll: Fehler alert("Interner Fehler bei der Umwandlung von CIDR zu Maske.");
alert("Interner Fehler bei der Umwandlung von CIDR zu Maske."); // Sollte nicht passieren bei gültigem CIDR
return; return;
} }
console.log(`CIDR converted to mask: ${subnetMask}`); // Protokoll: Erfolg
} }
// Berechnung durchführen und Ergebnisse anzeigen // Berechnung durchführen und Ergebnisse anzeigen
try { try {
console.log(`Calculating subnet for IP=${ipAddressInput}, CIDR=${cidr}`); // Protokoll: Vor Berechnung
const results = calculateSubnet(ipAddressInput, cidr); const results = calculateSubnet(ipAddressInput, cidr);
console.log("Calculation successful, results:", results); // Protokoll: Ergebnisse
displayResults(results, subnetMask); displayResults(results, subnetMask);
if (resultsDiv) { if (resultsDiv) {
resultsDiv.classList.remove('hidden'); // Ergebnisbereich sichtbar machen resultsDiv.classList.remove('hidden'); // Ergebnisbereich sichtbar machen
console.log("Results div made visible"); // Protokoll: Sichtbarkeit geändert
} else { } else {
console.error("Results div not found!"); // Protokoll: Fehler, falls Div fehlt console.error("Ergebnis-Div (ID: results) nicht gefunden!");
} }
} catch (error) { } catch (error) {
console.error("Error during subnet calculation:", error); // Protokoll: Ausnahme console.error("Fehler bei der Subnetzberechnung:", error);
alert("Fehler bei der Berechnung: " + error.message); alert("Fehler bei der Berechnung: " + error.message);
clearResults(); // Stellt sicher, dass der Ergebnisbereich bei Fehlern versteckt wird clearResults();
} }
console.log("handleSubnetCalculation finished"); // Protokoll: Ende
} }
// --- Validierungs- und Hilfsfunktionen --- // --- Validierungs- und Hilfsfunktionen ---
function isValidIP(ip) { function isValidIP(ip) {
// Einfacher Regex für IPv4
const ipPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; const ipPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return ipPattern.test(ip); return ipPattern.test(ip);
} }
function ipToBinary(ip) { function ipToBinary(ip) {
// Wandelt eine IP-Adresse (String) in einen 32-Bit-Binärstring um
return ip.split('.').map(octet => parseInt(octet, 10).toString(2).padStart(8, '0')).join(''); return ip.split('.').map(octet => parseInt(octet, 10).toString(2).padStart(8, '0')).join('');
} }
function binaryToIp(binary) { function binaryToIp(binary) {
// Wandelt einen 32-Bit-Binärstring in eine IP-Adresse (String) um if (binary.length !== 32) return null;
if (binary.length !== 32) return null; // Ungültige Länge
const octets = []; const octets = [];
for (let i = 0; i < 32; i += 8) { for (let i = 0; i < 32; i += 8) {
octets.push(parseInt(binary.substring(i, i + 8), 2)); octets.push(parseInt(binary.substring(i, i + 8), 2));
@@ -109,34 +88,28 @@ function binaryToIp(binary) {
} }
function cidrToMask(cidr) { function cidrToMask(cidr) {
// Wandelt eine CIDR-Zahl (0-32) in eine Subnetzmaske (String) um
if (cidr < 0 || cidr > 32) return null; if (cidr < 0 || cidr > 32) return null;
const maskBinary = '1'.repeat(cidr) + '0'.repeat(32 - cidr); const maskBinary = '1'.repeat(cidr) + '0'.repeat(32 - cidr);
return binaryToIp(maskBinary); return binaryToIp(maskBinary);
} }
function maskToCidr(mask) { function maskToCidr(mask) {
// Wandelt eine Subnetzmaske (String) in eine CIDR-Zahl um
if (!isValidIP(mask)) return null; if (!isValidIP(mask)) return null;
const binaryMask = ipToBinary(mask); const binaryMask = ipToBinary(mask);
// Prüfen, ob die Maske gültig ist (nur Einsen gefolgt von Nullen)
let encounteredZero = false; let encounteredZero = false;
for (let i = 0; i < 32; i++) { for (let i = 0; i < 32; i++) {
if (binaryMask[i] === '1') { if (binaryMask[i] === '1') {
if (encounteredZero) return null; // Eins nach Null -> ungültig if (encounteredZero) return null;
} else { } else {
encounteredZero = true; encounteredZero = true;
} }
} }
// Zähle die Einsen (CIDR)
let cidr = 0; let cidr = 0;
for(let i = 0; i < 32; i++) { for(let i = 0; i < 32; i++) {
if (binaryMask[i] === '1') { if (binaryMask[i] === '1') {
cidr++; cidr++;
} else { } else {
break; // Nach der ersten Null können keine Einsen mehr kommen break;
} }
} }
return cidr; return cidr;
@@ -156,15 +129,18 @@ function calculateSubnet(ip, cidr) {
const networkAddress = binaryToIp(networkBinary); const networkAddress = binaryToIp(networkBinary);
const networkNum = parseInt(networkBinary, 2); // Netzwerkadresse als Zahl const networkNum = parseInt(networkBinary, 2); // Netzwerkadresse als Zahl
// Broadcast-Adresse berechnen (Netzwerkadresse | invertierte Maske) // Broadcast-Adresse berechnen (Netzwerk-Teil + Host-Teil mit Einsen) - Korrigierte Methode
const invertedMaskBinary = '0'.repeat(cidr) + '1'.repeat(32 - cidr); const hostBitsCount = 32 - cidr;
const invertedMaskNum = parseInt(invertedMaskBinary, 2); let broadcastBinary = networkBinary.substring(0, cidr) + '1'.repeat(hostBitsCount);
const broadcastNum = networkNum | invertedMaskNum; // Sicherstellen, dass die Länge 32 Bit beträgt (sollte sie aber ohnehin)
const broadcastBinary = broadcastNum.toString(2).padStart(32, '0'); broadcastBinary = broadcastBinary.padEnd(32, '1'); // Auffüllen mit 1, falls Länge < 32 (unwahrscheinlich)
const broadcastAddress = binaryToIp(broadcastBinary); const broadcastAddress = binaryToIp(broadcastBinary);
// broadcastNum wird für die letzte Host-Adresse benötigt
const broadcastNum = parseInt(broadcastBinary, 2);
// Anzahl der Hosts // Anzahl der Hosts
const hostBits = 32 - cidr; const hostBits = 32 - cidr; // hostBitsCount umbenannt für Konsistenz
let hostCount = 0; let hostCount = 0;
if (hostBits >= 2) { // Mindestens /30 für 2 Hosts (-2) if (hostBits >= 2) { // Mindestens /30 für 2 Hosts (-2)
hostCount = Math.pow(2, hostBits) - 2; hostCount = Math.pow(2, hostBits) - 2;
@@ -177,7 +153,9 @@ function calculateSubnet(ip, cidr) {
// Erste Host-Adresse // Erste Host-Adresse
let firstHost = '-'; let firstHost = '-';
if (hostBits >= 2) { // /30 oder größer: Netzwerkadresse + 1 if (hostBits >= 2) { // /30 oder größer: Netzwerkadresse + 1
const firstHostBinary = (networkNum + 1).toString(2).padStart(32, '0'); // Sicherstellen, dass die Addition korrekt behandelt wird (als Zahl)
const firstHostNum = networkNum + 1;
const firstHostBinary = firstHostNum.toString(2).padStart(32, '0');
firstHost = binaryToIp(firstHostBinary); firstHost = binaryToIp(firstHostBinary);
} else if (cidr === 31) { // /31: Die erste Adresse des /31 } else if (cidr === 31) { // /31: Die erste Adresse des /31
firstHost = networkAddress; firstHost = networkAddress;
@@ -188,7 +166,9 @@ function calculateSubnet(ip, cidr) {
// Letzte Host-Adresse // Letzte Host-Adresse
let lastHost = '-'; let lastHost = '-';
if (hostBits >= 2) { // /30 oder größer: Broadcast-Adresse - 1 if (hostBits >= 2) { // /30 oder größer: Broadcast-Adresse - 1
const lastHostBinary = (broadcastNum - 1).toString(2).padStart(32, '0'); // Sicherstellen, dass die Subtraktion korrekt behandelt wird (als Zahl)
const lastHostNum = broadcastNum - 1;
const lastHostBinary = lastHostNum.toString(2).padStart(32, '0');
lastHost = binaryToIp(lastHostBinary); lastHost = binaryToIp(lastHostBinary);
} else if (cidr === 31) { // /31: Die zweite Adresse des /31 } else if (cidr === 31) { // /31: Die zweite Adresse des /31
lastHost = broadcastAddress; lastHost = broadcastAddress;
@@ -208,11 +188,8 @@ function calculateSubnet(ip, cidr) {
// --- Anzeige-Funktionen --- // --- Anzeige-Funktionen ---
function displayResults(results, subnetMask) { function displayResults(results, subnetMask) {
console.log("Displaying results:", results, "with mask:", subnetMask); // Protokoll: Anzeige
// Ergebnisse in die entsprechenden HTML-Elemente schreiben
document.getElementById('network-address').textContent = results.networkAddress; document.getElementById('network-address').textContent = results.networkAddress;
document.getElementById('broadcast-address').textContent = results.broadcastAddress; document.getElementById('broadcast-address').textContent = results.broadcastAddress;
// Zeige Host Count nur an, wenn sinnvoll (>=0)
document.getElementById('host-count').textContent = results.hostCount >= 0 ? results.hostCount.toLocaleString() : '-'; document.getElementById('host-count').textContent = results.hostCount >= 0 ? results.hostCount.toLocaleString() : '-';
document.getElementById('first-host').textContent = results.firstHost; document.getElementById('first-host').textContent = results.firstHost;
document.getElementById('last-host').textContent = results.lastHost; document.getElementById('last-host').textContent = results.lastHost;
@@ -220,8 +197,6 @@ function displayResults(results, subnetMask) {
} }
function clearResults() { function clearResults() {
console.log("Clearing results and hiding results div"); // Protokoll: Löschen
// Setzt die Ergebnis-Felder zurück und versteckt den Bereich
document.getElementById('network-address').textContent = '-'; document.getElementById('network-address').textContent = '-';
document.getElementById('broadcast-address').textContent = '-'; document.getElementById('broadcast-address').textContent = '-';
document.getElementById('host-count').textContent = '-'; document.getElementById('host-count').textContent = '-';