Skip to content

Instantly share code, notes, and snippets.

@aa65535
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aa65535/6483d6c920903f29d634 to your computer and use it in GitHub Desktop.
Save aa65535/6483d6c920903f29d634 to your computer and use it in GitHub Desktop.
Use CIDR match given two ip address.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CIDR Match</title>
</head>
<body>
<table>
<tbody>
<tr>
<td>IP1</td>
<td><input type="text" id="ip1" onkeyup="_gen()"></td>
</tr>
<tr>
<td>IP2</td>
<td><input type="text" id="ip2" onkeyup="_gen()"></td>
</tr>
<tr>
<td>CIDR</td>
<td><input type="text" id="cidr" onclick="this.select()" readonly></td>
</tr>
</tbody>
</table>
<script>
function pad_l(s, l) {
while (s.length < l) {
s = '0' + s;
}
return s;
}
function pad_r(s, l) {
while (s.length < l) {
s += '0';
}
return s;
}
function ip2bin(ip) {
var i,
bin = '',
a = ip.split('.');
if (a.length !== 4) {
return '';
}
for (i = 0; i < 4; i++) {
if (a[i] < 0 || a[i] > 255) {
return '';
}
bin += pad_l(parseInt(a[i], 10).toString(2), 8);
}
return bin;
}
function bin2ip(bin) {
if (bin.length === 32) {
return [
parseInt(bin.slice(0, 8), 2),
parseInt(bin.slice(8, 16), 2),
parseInt(bin.slice(16, 24), 2),
parseInt(bin.slice(-8), 2)
].join('.');
}
return '';
}
function cidr_match(ip1, ip2) {
var i, t = '',
a = ip2bin(ip1),
b = ip2bin(ip2);
if (!a || !b) {
return '';
}
for (i = 0; i < 32; i++) {
if (a[i] == b[i]) {
t += a[i];
continue;
}
break;
}
return bin2ip(pad_r(t, 32)) + '/' + i;
}
function _gen() {
var ip1 = document.getElementById('ip1').value;
var ip2 = document.getElementById('ip2').value;
document.getElementById('cidr').value = cidr_match(ip1, ip2);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment