Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id="container">
  <form>
    <h1>Calculadora IP</h1>

    <h2>Digite o IP</h2>

    <input type="text" placeholder="Ex:192.168.0.100" pattern="^(\d{1,3}\.){3}\d{1,3}$" maxlength="15" title="Formato decimal incluído os pontos" id="ip" />

    <h2>Digite a máscara</h2>

    <input type="text" placeholder="Ex:255.255.255.0" pattern="^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}$" maxlength="15" title="Formato decimal incluído os pontos" id="mascara"/>

    <p>ou /</p>

    <input type="number" name="mascaraCIDR" placeholder="Ex:/24" pattern="^\d{1,2}$" maxlength="2" title="1 ou 2 dígitos" id="mascaraCIDR" />
  
    <button id="botao">Calcular</button>
  </form>
  
  <pre>
    <div id="resultadoClasse"></div>
    <div id="resultadoIP"></div>
    <div id="resultadoMascara"></div>
    <div id="resultadoRede"></div>
    <div id="resultadoBroadcast"></div>
    <div id="resultadoQtdRede"></div>
    <div id="resultadoQtdHost"></div>
  <pre>

</div>
            
          
!
            
              @import url('https://fonts.googleapis.com/css?family=Roboto');

*{
  box-sizing: border-box;
  margin: 0 auto;
  padding: 0;
  font-family:Roboto, Arial, sans-serif;
  box-sizing: border-box;
}

div#container{
  width: 50%;
}

@media only screen and (max-width: 800px) {
  div#container{
    width: 90%;
  }
}
div#container form  h1{
  text-shadow: 1px 1px 1px black;
}

div#container input{
  border-top: 0;
  border-left: 0;
  border-right: 0;
  width: 100%;
  height: 2.5rem;
}

div#container button{
  font-size: 2.1rem;
  width: 50%;
  height: 3.125rem;
  border: 0;
  background-color: #3330ff;
  color: #f7f7f7;
  -webkit-border-radius: 1em;
  -moz-border-radius: 1em;
  border-radius: 1em;
  margin: 25px 25%;
  box-shadow: 0 0 10px black;
}

div#container button:hover{
  background-color: #f7f7f7;
  color: #3330ff;
  cursor: pointer;
}

div#container button:active{
  color: #2979FF;
}

pre{
 background-color: #f6f8fa;
 border-radius: 3px;
 box-sizing: border-box;
 color: #24292e;
 font-family: SFMono-Regular, Consolas, Menlo, Courier, monospace;
 font-size: 13.6px;
 line-height: 1.45;
 margin-bottom: 16px;
 overflow: auto;
 padding: 16px;
 word-wrap: normal;
}

            
          
!
            
              function separarOcteto(decimal) {
  return decimal.split(".");
}

//verificar se está faltando digitos para completa o octeto
function verificarOcteto(octeto) {
  var octetoAux = new String(octeto);

  diferenca = Math.abs(octetoAux.length - 8);

  if (octetoAux.length < 8) { 
    for (var i = 0; i < diferenca; i++) {
      octetoAux = "0" + octetoAux;
    }
  }
  return octetoAux;
}

//verificar a classe ip, mas precisa da forma binária
function verificarClasseIp(primeiroOcteto) {
  var aux = new String(primeiroOcteto);

  if (aux.slice(0, 1) == "0") {
    return "A";
  } else if (aux.slice(0, 2) == "10") {
    return "B";
  } else if (aux.slice(0, 3) == "110") {
    return "C";
  } else if (aux.slice(0, 4) == "1110") {
    return "D";
  } else if (aux.slice(0, 5) == "1111") {
    return "E";
  }
}

function unir(octeto1, octeto2, octeto3, octeto4) {
  return new String(octeto1 + "." + octeto2 + "." + octeto3 + "." + octeto4);
}

function verificarRede(ip, mascara) {
  var rede = new String();

  for (var i = 0; i < 35; i++) {
    //operção AND entre ip e máscara
    if (ip.charAt(i) == '1' && mascara.charAt(i) == '1') {
      rede += "1"
    } else if ((ip.charAt(i) == '0' && mascara.charAt(i) == '1') || (ip.charAt(i) == '1' && mascara.charAt(i) == '0') || (ip.charAt(i) == '0' && mascara.charAt(i) == '0')) {
      rede += "0"
    } else {
      rede += "."
    }
  }

  return rede;
}

function verificarBroadcast(ip, mascara) {
  var notMascara = new String();

  for (var i = 0; i < 35; i++) {
    //operção NOT na máscara
    if (mascara.charAt(i) == '1') {
      notMascara += "0"
    } else if (mascara.charAt(i) == '0') {
      notMascara += "1"
    } else {
      notMascara += "."
    }
  }

  var broadcast = new String();

  for (var i = 0; i < 35; i++) {
    //operção OR entre ip e o not da máscara
    if ((notMascara.charAt(i) == '1' && ip.charAt(i) == '1') || (notMascara.charAt(i) == '0' && ip.charAt(i) == '1') || (notMascara.charAt(i) == '1' && ip.charAt(i) == '0')) {
      broadcast += "1"
    } else if ((notMascara.charAt(i) == '0' && ip.charAt(i) == '0')) {
      broadcast += "0"
    } else {
      broadcast += "."
    }
  }

  return broadcast;
}

function notacaoCIDR(mascara) {
  // exemplo /24

  var mascaraCIDR = new String();

  if (verificarNotacaoCIDR(mascara)) {
    for (var i = 0; i < 35; i++) {
      if (i == 8 || i == 17 || i == 26) {
        mascaraCIDR += ".";
        continue;
      }
      if (mascara != 0) {
        mascaraCIDR += "1";
        mascara--;
      } else if (i > mascara) {
        mascaraCIDR += "0";
      }
    }
    return mascaraCIDR;
  }

  return "cidr error"
}

function verificarNotacaoCIDR(mascara) {
  if (mascara > 0 && mascara <= 32) {
    return true;
  }
  return false;
}

function calcularSubrede(ip, mascara) {
  switch (verificarClasseIp(ip)) {
    case 'A':
      return new Number(Math.pow(2, Math.abs(8 - qtdBitsLigado(mascara))));
    case 'B':
      return new Number(Math.pow(2, Math.abs(16 - qtdBitsLigado(mascara))));
    case 'C':
      return new Number(Math.pow(2, Math.abs(24 - qtdBitsLigado(mascara))));
    default:
      break;
  }
}

function qtdBitsLigado(mascara) {
  aux = 0;

  for (var i = 0; i < 35; i++) {
    if (mascara[i] == 1) {
      aux++;
    }
  }
  return aux;
}

function calcularHost(mascara) {
  return new Number(Math.pow(2, qtdBitsDesligado(mascara)) - 2);
}

function qtdBitsDesligado(mascara) {
  aux = 0;

  for (var i = 0; i < 35; i++) {
    if (mascara[i] == 0) {
      aux++;
    }
  }
  return aux;
}

function validarIp(ip, ipbase10) {

  var regExp = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;

  if (regExp.test(ip)) {
    if (ipbase10[0] == 0) {
      return false;
    } else
      if (((ipbase10[0] > 0) && (ipbase10[0] <= 255) &&
           (ipbase10[1] >= 0) && (ipbase10[1] <= 255)) &&
          ((ipbase10[2] >= 0) && (ipbase10[2] <= 255) &&
           (ipbase10[3] >= 0) && (ipbase10[3] <= 255))) {
        return true;
      } else {
        return false;
      }
  } else {
    console.log("Ip inválido!!!")
    return false;
  }
}

function validarMascara(octeto1IP, mascara) {
  var regExp = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;

  if (regExp.test(unir(mascara[0], mascara[1], mascara[2], mascara[3]))) {
    switch (verificarClasseIp(octeto1IP)) {
      case 'A':

        if (mascara[0] != "255") {
          console.log("Máscara inválida!!!")
          return false;
        } else if ((mascara[1] >= 0 && mascara[1] <= 255) && (mascara[2] == '0' && mascara[3] == '0')) {
          console.log("Máscara válida!!!")
          return true;
        } else if ((mascara[1] == 255 && (mascara[2] >= 0 && mascara[2] <= 255)) && mascara[3] == 0) {
          console.log("Máscara válida!!!");
          return true;
        } else if ((mascara[1] == 255 && mascara[2] == 255) && (mascara[3] >= 0 && mascara[3] <= 255)) {
          console.log("Máscara válida!!!");
          return true;
        } else {
          console.log("Máscara invalida!!!")
          return false;
        }
      case 'B':
        if ((mascara[0] != "255") || (mascara[1] != "255")) {
          console.log("Máscara invalida!!!")
          return false;
        } else if ((mascara[2] >= "0" && mascara[2] <= "255") && mascara[3] == 0) {
          console.log("Máscara válida!!!")
          return true;
        } else if (mascara[2] == "255" && (mascara[3] >= 0 && mascara[3] <= 255)) {
          console.log("Máscara válida!!!")
          return true;
        } else {
          console.log("Máscara inválida!!!")
          return false;
        }
      case 'C':
        if (((mascara[0] != "255") || (mascara[1] != "255")) || (mascara[2] != "255")) {
          console.log("Máscara invalida!!!")
          return false;
        } else if (mascara[3] >= 0 && mascara[3] <= 255) {
          console.log("Máscara válida!!!")
          return true;
        }
      case 'D':
        console.log("IP para Multicast")
        return false;
      case 'E':
        console.log("Reservada a testes pela IETF")
        return false;
      default:
        console.log("Error!!!")
        return false;
    }
  } else {
    console.log("Máscara inválida!!!");
    return false;
  }

}

function converteDecimal(binario) {
  var binarioSeparado = separarOcteto(binario);
  var decimal = new Array();

  for (var i = 0; i < binarioSeparado.length; i++) {
    decimal.push(parseInt(binarioSeparado[i], 2).toString());
  }
  return unir(decimal[0], decimal[1], decimal[2], decimal[3]);
}

// -------------------------------

var botao = document.getElementById("botao");
var resultado = document.getElementById("resultado")

function calcularIP() {

  var ip = document.getElementById("ip").value;
  var mascara = document.getElementById("mascara").value;
  var cidr = document.getElementById("mascaraCIDR").value;

  if(!mascara){
    mascara = converteDecimal(notacaoCIDR(cidr));
  }

  var ipDecimal = separarOcteto(ip);
  var mascaraDecimal = separarOcteto(mascara);

  var octeto1ip = verificarOcteto(parseInt(ipDecimal[0]).toString(2));
  var octeto2ip = verificarOcteto(parseInt(ipDecimal[1]).toString(2));
  var octeto3ip = verificarOcteto(parseInt(ipDecimal[2]).toString(2));
  var octeto4ip = verificarOcteto(parseInt(ipDecimal[3]).toString(2));

  var octeto1mascara = verificarOcteto(parseInt(mascaraDecimal[0]).toString(2));
  var octeto2mascara = verificarOcteto(parseInt(mascaraDecimal[1]).toString(2));
  var octeto3mascara = verificarOcteto(parseInt(mascaraDecimal[2]).toString(2));
  var octeto4mascara = verificarOcteto(parseInt(mascaraDecimal[3]).toString(2));

  var ipBinario = unir(octeto1ip, octeto2ip, octeto3ip, octeto4ip);
  var mascaraBinario = unir(octeto1mascara, octeto2mascara, octeto3mascara, octeto4mascara);

  if (validarIp(ip, ipDecimal)) {
    if (validarMascara(octeto1ip, mascaraDecimal)) {

      var resultClasse = document.getElementById("resultadoClasse");
      var resultIP = document.getElementById("resultadoIP");
      var resultMascara = document.getElementById("resultadoMascara");
      var resultRede = document.getElementById("resultadoRede");
      var resultBroadcast = document.getElementById("resultadoBroadcast");
      var resultQtdRede = document.getElementById("resultadoQtdRede");
      var resultQtdHost = document.getElementById("resultadoQtdHost");

      resultClasse.innerHTML = "<hr /><h5>Classe IP</h5><h5>" +verificarClasseIp(octeto1ip)  + "</h5>";
      resultIP.innerHTML = "<hr /><h5>Endereço IP</h5><h5>" + ip + "</h5><h5>" + ipBinario.toString() + "</h5>";
      resultMascara.innerHTML = "<hr /><h5>Máscara</h5><h5>" + mascara + "</h5><h5>" + mascaraBinario.toString() + "</h5>";
      resultRede.innerHTML = "<hr /><h5>Endereço de Rede</h5><h5>" + converteDecimal(verificarRede(ipBinario, mascaraBinario)).toString() + "</h5><h5>" + verificarRede(ipBinario, mascaraBinario) + "</h5>";
      resultBroadcast.innerHTML = "<hr /><h5>Endereço de Broadcast</h5><h5>" + converteDecimal(verificarBroadcast(ipBinario, mascaraBinario)).toString() + "</h5><h5>" + verificarBroadcast(ipBinario, mascaraBinario) + "</h5>";
      resultQtdRede.innerHTML = "<hr /><h5>Quantidade de rede/sub-rede</h5><h5>" + calcularSubrede(ipBinario, mascaraBinario).toString() + "</h5>";
      resultQtdHost.innerHTML = "<hr /><h5>Quantidade de host por rede/sub-rede</h5><h5>" + calcularHost(mascaraBinario).toString() + "</h5>";

    }else{
      var resultClasse = document.getElementById("resultadoClasse");
      resultClasse.innerHTML = "<hr /><h3 style='color:red' >Verifique a máscara</h3>";
    }
  }else{
    var resultClasse = document.getElementById("resultadoClasse");
    resultClasse.innerHTML = "<hr /><h3 style='color:red' >Verifique o IP</h3>";
  }

};

var form = document.querySelector("form");

form.addEventListener("submit", function(evento){
  evento.preventDefault();
  limparCampos();
  calcularIP();
});

function limparCampos(){
  document.getElementById("resultadoClasse").innerHTML="";
  document.getElementById("resultadoIP").innerHTML="";
  document.getElementById("resultadoMascara").innerHTML="";
  document.getElementById("resultadoRede").innerHTML="";
  document.getElementById("resultadoBroadcast").innerHTML="";
  document.getElementById("resultadoQtdRede").innerHTML="";
  document.getElementById("resultadoQtdHost").innerHTML="";
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console