Pen Settings

HTML

CSS

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

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <header class="header">
  <h1>Calculadora IP</h1>
</header>

<main class="main">
  <section class="inputData">
    <form>
      <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" />
      </br>
    <button class="button">Calcular</button>
    </form>
  </section>
</main>
              
            
!

CSS

              
                *{
  box-sizing: border-box; 
  margin: 0;
  padding: 0;
}

body{
  font-family: 'Open Sans', sans-serif;
  font-family: 'Rubik', sans-serif;
}

a{
  text-decoration: none;
}

ul, ol, li{
  list-style: none; 
}

input, input::placeholder {
  font-family: 'IBM Plex Mono', monospace;
}

section {
  width: 100%;
}

input {
  width: 100%;
  height: 60px;
  color: #333;
  border: 1px solid #dcdce6;
  border-radius: 8px;
  padding: 0 24px;
  margin: 12px 0;
  background-color: #dadede;
}

button {
  cursor: pointer;
}

.button {
  width: 60%;
  max-width: 400px;
  height: 60px;
  background: #72a2cf;
  border: 0;
  border-radius: 8px;
  color: #fff;
  font-weight: 700;
  margin: 16px auto; 
  display: block;
  text-align: center;
  text-decoration: none;
  font-size: 18px;
  line-height: 60px;
  transition: filter 0.2s;
  border-radius: 25px;
  box-shadow:0px 4px 6px #2522229d ;
}

.button:hover {
  filter: brightness(90%);
}

.button:active {
  box-shadow: inset 0px 4px 6px #2522229d;
  filter: brightness(80%);
}

.main {
  margin: 10px 20px;
}

.header {
  width: 100%;
  height: 10vh;
  min-height: 40px;
  background-color: #536DFE;
  color: #FFFFFF;
  text-align: center;
  line-height: 10vh;
}

.result {
  font-family: 'IBM Plex Mono', monospace;
  overflow-wrap: break-word;
}

.result .card {
  box-shadow: 0 2px 8px 2px rgba(0,0,0,0.3);
  transition: 0.3s;
  background-color: #ECEFF1; 
  margin: 10px 0;
  padding: 5px;
}

.result .card:hover {
  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.3);
}

.result .card > :first-child {
  background: rgba(88, 150, 231, 0.829);
  font-weight: bold;
  text-align: center;
  padding: 3px;
  color: rgb(25, 29, 41);
}

.alert {
  display: block;
  width: 100%;
  height: 50px; 
  text-align: center;
  line-height: 50px; 
  font-size: large;
  position: fixed;
  bottom: 10px;
  right: 0;
  box-shadow: 0 0 4px #333;
}

.warning {
  background-color: #e8263c;
  color: white;
  font-weight: bold;
}

@media screen and (min-width: 900px) {
  .main {
    margin: 20px 60px;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
  }

  section {
    margin: 0 15px;
  }

}

@media screen and (max-height: 430px) {
  .header {
    height: 50px;
    line-height: 50px;
  }
  
  .header h1 {
    line-height: inherit;
  }
  
  .alert {
    position: static;
    margin: 15px 0;
  }

}
              
            
!

JS

              
                "use strict";

function verificarClasse(ip) {
  ip = validarEntrada(ip);
  return tipoClasse(primeiroOcteto(ip));
}

function validarEntrada(value) {
  if (ehVazio(value)) {
    throw new Error("Parse algum valor por parâmetro");
  }

  if (!ehString(value)) {
    throw new Error("O parâmeto deve ser do tipo String");
  }

  value = value.trim();

  if (!ehValidoMascaraOrIP(value)) {
    throw new Error(
      "Utilize pontos para separar os valores e não deixe espaços"
    );
  }

  return value;
}

function ehVazio(value) {
  return !!!value;
}

function ehString(value) {
  return typeof value === "string";
}

function ehValidoMascaraOrIP(value) {
  const regExp = /^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][1-9]|2[0-5][0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][1-9]|2[0-5][0-5])$/;
  return regExp.test(value);
}

function converterDecimalParaBinario(decimal) {
  return (decimal >>> 0).toString(2);
}

function primeiroOcteto(value) {
  value = value.split(".");
  value = converterDecimalParaBinario(value[0]);
  return preencherOcteto(value);
}

function preencherOcteto(value) {
  return "00000000".slice(value.length) + value;
}

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

function verificarMascara(mascara, classeIp) {
  mascara = validarEntrada(mascara);

  if (classeIp === "A") {
    const regExp = /^(((255)\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5]))\.0\.0)|((((255)\.){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5]))\.0)|((((255)\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5])))$/;
    return regExp.test(mascara);
  }

  if (classeIp === "B") {
    const regExp = /^((((255)\.){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5]))\.0)|((((255)\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5])))$/;
    return regExp.test(mascara);
  }

  if (classeIp === "C") {
    const regExp = /^((((255)\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5])))$/;
    return regExp.test(mascara);
  }

  return false;
}

/* 
   Operação AND entre IP e Máscara
*/
function verificarRede(ip, mascara) {
  ip = converterDecimalParaBinarioQuatroOctetos(ip);
  mascara = converterDecimalParaBinarioQuatroOctetos(mascara);

  let rede = "";

  for (let i = 0; i < ip.length; i++) {
    let ipBin = ip.charAt(i);
    let mascaraBin = mascara.charAt(i);

    if (ipBin === "." || mascaraBin === ".") {
      rede += ipBin || mascaraBin;
    } else {
      rede += ipBin & mascaraBin;
    }
  }

  return converteBinarioParaDecimalQuatroNumeros(rede);
}

/* 
    Operação OR entre IP e o NOT da Máscara
*/
function verificarBroadcast(ip, mascara) {
  ip = converterDecimalParaBinarioQuatroOctetos(ip);
  mascara = negacaoBinariaQuatroOctetos(
    converterDecimalParaBinarioQuatroOctetos(mascara)
  );

  let broadcast = "";

  for (let i = 0; i < ip.length; i++) {
    let ipBin = ip.charAt(i);
    let mascaraBin = mascara.charAt(i);

    if (ipBin === "." || mascaraBin === ".") {
      broadcast += ".";
    } else {
      broadcast += ipBin | mascaraBin;
    }
  }

  return converteBinarioParaDecimalQuatroNumeros(broadcast);
}

function converterDecimalParaBinarioQuatroOctetos(value) {
  value = value.split(".");
  let octetos = preencherOcteto(converterDecimalParaBinario(value[0]));
  octetos += "." + preencherOcteto(converterDecimalParaBinario(value[1]));
  octetos += "." + preencherOcteto(converterDecimalParaBinario(value[2]));
  octetos += "." + preencherOcteto(converterDecimalParaBinario(value[3]));
  return octetos;
}

function converterBinarioParaDecimal(value) {
  return parseInt(value, 2);
}

function converteBinarioParaDecimalQuatroNumeros(value) {
  value = value.split(".");
  let numeros = converterBinarioParaDecimal(value[0]);
  numeros += "." + converterBinarioParaDecimal(value[1]);
  numeros += "." + converterBinarioParaDecimal(value[2]);
  numeros += "." + converterBinarioParaDecimal(value[3]);
  return numeros;
}

function negacaoBinaria(value) {
  return value === "1" ? "0" : "1";
}

function negacaoBinariaQuatroOctetos(value) {
  let valueNegado = "";
  for (let i = 0; i < value.length; i++) {
    let valueBin = value.charAt(i);
    if (valueBin === ".") {
      valueNegado += valueBin;
    } else {
      valueNegado += negacaoBinaria(valueBin);
    }
  }
  return valueNegado;
}

function notacaoCIDR(value) {
  let mascaraCIDR = "";

  for (let i = 0; i < 32; i++) {
    if (i < value) {
      mascaraCIDR += "1";
    } else {
      mascaraCIDR += "0";
    }
  }

  mascaraCIDR = converteBinarioParaDecimalQuatroNumeros(
    formatarBinarioQuatroOctetos(mascaraCIDR)
  );
  return mascaraCIDR;
}

function formatarBinarioQuatroOctetos(value) {
  let octeto = value.slice(0, 8);
  octeto += "." + value.slice(8, 16);
  octeto += "." + value.slice(16, 24);
  octeto += "." + value.slice(24, 32);
  return octeto;
}

function verificarSubrede(classeIp, mascara) {
  mascara = converterDecimalParaBinarioQuatroOctetos(mascara);
  switch (classeIp) {
    case "A":
      return Math.pow(2, Math.abs(8 - qtdBitsLigado(mascara)));
    case "B":
      return Math.pow(2, Math.abs(16 - qtdBitsLigado(mascara)));
    case "C":
      return Math.pow(2, Math.abs(24 - qtdBitsLigado(mascara)));
    default:
      throw new Error("Não foi possível calcular a subrede");
  }
}

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

function qtdBitsLigado(mascara) {
  return mascara.match(/1/g).length;
}

function qtdBitsDesligado(mascara) {
  return mascara.match(/0/g).length;
}

const $form = document.querySelector("form");

const $ip = document.getElementById("ip");
const $mascara = document.getElementById("mascara");
const $mascaraCIDR = document.getElementById("mascaraCIDR");

$form.addEventListener("submit", function(e) {
  e.preventDefault();

  limparCampos();

  try {
    if (!!$mascaraCIDR.value) {
      $mascara.value = notacaoCIDR($mascaraCIDR.value);
    }
    const classe = verificarClasse($ip.value);
    const mascara = verificarMascara($mascara.value, classe);
    const rede = verificarRede($ip.value, $mascara.value);
    const broadcast = verificarBroadcast($ip.value, $mascara.value);
    const host = verificarHost($mascara.value);
    const subrede = verificarSubrede(classe, $mascara.value);

    /* section result */

    const $secaoDeEntrada = document.querySelector('section');
    $secaoDeEntrada.insertAdjacentHTML('afterend', `<section class="result"></section>`);

    /* card */

    const $secaoResultado = document.querySelector('.result');

    $secaoResultado.insertAdjacentHTML('beforeend', criarCard('Classe', classe));

    $secaoResultado.insertAdjacentHTML('beforeend', criarCard('IP', ip.value, converterDecimalParaBinarioQuatroOctetos($ip.value)));

    $secaoResultado.insertAdjacentHTML('beforeend', criarCard('Máscara', $mascara.value, converterDecimalParaBinarioQuatroOctetos($mascara.value)));

    $secaoResultado.insertAdjacentHTML('beforeend', criarCard('Endereço de Rede', rede, converterDecimalParaBinarioQuatroOctetos(rede)));

    $secaoResultado.insertAdjacentHTML('beforeend', criarCard('Endereço de Broadcast', broadcast, converterDecimalParaBinarioQuatroOctetos(broadcast)));

    $secaoResultado.insertAdjacentHTML('beforeend', criarCard('Quantidade de rede/sub-rede', subrede));

    $secaoResultado.insertAdjacentHTML('beforeend', criarCard('Quantidade de host por rede/sub-rede', host));

  } catch (error) {
    document.querySelector('body').insertAdjacentHTML('beforeend', 
                             `<div class="result alert warning">
                                <p>Verifique os valores inseridos</p>
                              </div>`
   )}
});

function limparCampos(){
  document.querySelector('.result') ? document.querySelector('.result').remove() : "";
}

function criarCard(texto, valor1, valor2) {
  if (!!valor2) {
    return `<div class="card">
              <p>${texto}</p>
              <p>${valor1}</p>
              <p>${valor2}</p>
            </div>`
  } else {
    return `<div class="card">
              <p>${texto}</p>
              <p>${valor1}</p>
            </div>`
  }
}
              
            
!
999px

Console