IP Calculator in JS

Asked

Viewed 693 times

-1

Hello. I need to develop a Javascript network calculator that discovers the broadcast address and network address from the IP address (Ipv4) and network mask. But I have no idea how to do that. I thank you in advance!

  • 3

    Question XY?

  • 3

    Ipv4 only or Ipv6 also?

1 answer

2

Follow the code I made. Only works for Ipv4:

function IPv4(input) {

    // Se o input já for um IPv4, não cria um objeto novo.
    if (input instanceof IPv4) return input;

    // Se o "new" tiver sido omitido, faz a chamada com ele.
    if (!(this instanceof IPv4)) return new IPv4(input);

    // Se o input for uma string, a separa em partes.
    if (typeof input === "string") {
        var partes = input.split(".");
        return new IPv4(partes);
    }

    // Se o input não for nem string, nem array e nem um outro IPv4, então desiste.
    if (!(input instanceof Array)) {
        throw "IPv4 inválido (tentativa de construir com entrada de tipo não-reconhecido): '" + input.join(".") + "'.";
    }

    // Neste ponto, o input só pode ser um array. Se não tiver exatamente quatro elementos, é mal-formado.
    if (input.length !== 4) {
        throw "IPv4 inválido (não tem quatro partes): '" + input.join(".") + "'.";
    }

    // Separa os quatro elementos do array e garante que sejam números.
    var m1, m2, m3, m4;
    try {
        var m1 = parseInt(input[0], 10);
        var m2 = parseInt(input[1], 10);
        var m3 = parseInt(input[2], 10);
        var m4 = parseInt(input[3], 10);
    } catch (e) {
        throw "IPv4 inválido (valores não numéricos): '" + input.join(".") + "'.";
    }

    // O parseInt é muito leniente quanto a textos mal-formados. Aqui verificamos se esse foi o caso.
    if ("" + m1 !== "" + input[0] || "" + m2 !== "" + input[1] || "" + m3 !== "" + input[2] || "" + m4 !== "" + input[3]) {
        throw "IPv4 inválido (partes com trechos não reconhecidos): '" + input.join(".") + "'.";
    }

    // Verifica se todos os valores estão na faixa correta.
    if (m1 < 0 || m1 > 255 || m2 < 0 || m2 > 255 || m3 < 0 || m3 > 255 || m4 < 0 || m4 > 255) {
        throw "IPv4 inválido (valores fora da faixa 0-255): '" + input.join(".") + "'.";
    }

    this.partes = function() {
        return [m1, m2, m3, m4];
    };

    this.and = function(outro) {
        var p2 = outro.partes();
        return new IPv4([m1 & p2[0], m2 & p2[1], m3 & p2[2], m4 & p2[3]]);
    };

    this.or = function(outro) {
        var p2 = outro.partes();
        return new IPv4([m1 | p2[0], m2 | p2[1], m3 | p2[2], m4 | p2[3]]);
    };

    this.not = function() {
        return new IPv4([~m1 & 0xFF, ~m2 & 0xFF, ~m3 & 0xFF, ~m4 & 0xFF]);
    };

    this.toString = function() {
        return m1 + "." + m2 + "." + m3 + "." + m4;
    };

    this.mascarar = function(mascara) {
        mascara = IPv4(mascara);

        return {
            rede: this.and(mascara),
            broadcast: this.or(mascara.not())
        };
    };
}

document.getElementById("botaoCalcular").onclick = function() {
    var ip = document.getElementById("ip").value;
    var mascara = document.getElementById("mascara").value;

    try {
        calculado = IPv4(ip).mascarar(mascara);
        document.getElementById("rede").value = calculado.rede;
        document.getElementById("broadcast").value = calculado.broadcast;
        document.getElementById("erro").innerHTML = "";
    } catch (e) {
        document.getElementById("rede").value = "Erro!";
        document.getElementById("broadcast").value = "Erro!";
        document.getElementById("erro").innerHTML = e;
    }
};
<p>
    Entre com o endereço IPv4: <input type="text" id="ip" value="192.168.28.70" />
</p>
<p>
    Entre com a máscara de rede: <input type="text" id="mascara" value="255.255.255.0" />
</p>
<p>
    <input type="button" id="botaoCalcular" value="Calcular" />
</p>
<p>
    Endereço de rede: <input type="text" id="rede" value="" readonly />
</p>
<p>
    Endereço de broadcast: <input type="text" id="broadcast" value="" readonly />
</p>
<p id="erro"></p>

Click on the blue button "Execute" above to test and play.

The function IPv4 creates an object that represents an Ipv4 address. A lot of your code is to validate whether your parameter (a string or an array) is well formed and to parse it, separating the four numbers from Ipv4 (the code comments explain each of the steps of this process).

Ipv4 is actually a set of 32 bits represented in four 8-bit numbers each. The calculation of the network address and the broadcast address is obtained by combining the corresponding bits of the IP address with that of the network mask, each position being independent of the others. That is, the calculation of bit 12 (for example) of the network address and the broadcast is totally independent of the calculation made with bit 11 or with 13 or with any other bit.

In javascript, we have bitwise operators &, | and ~ to do the E, OU and NÃO bit-a-bit. They are used in methods and, or and not of the object IPv4.

The network address is obtained with the formula IP AND MASCARA, whereas the broadcast address is IP OR NOT MASCARA, transactions performed bit-by-bit. The method mascarar is the one that invokes those operations on the IP address, producing both results.

This code follows the MVC standard. The function IPv4 is the template. HTML is the view. The javascript that is after the function IPv4 manipulating the document and connecting the model and vision is the controller.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.