Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Counting the number of IP addresses present between two IP addresses in JavaScript
We are required to write a JavaScript function that takes in two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).
This can be done by converting them to decimal and finding their absolute difference.
How IP Address Conversion Works
An IPv4 address consists of 4 octets (0-255). To convert to decimal, we use the formula:
Example Implementation
const ip1 = '20.0.0.10';
const ip2 = '20.0.1.0';
const countIp = (ip1, ip2) => {
let diff = 0;
const aIp1 = ip1.split(".");
const aIp2 = ip2.split(".");
// Validate IP format
if (aIp1.length !== 4 || aIp2.length !== 4) {
return "Invalid IPs: incorrect format";
}
// Validate each octet and calculate difference
for (let x = 0; x < 4; x++) {
if (
isNaN(aIp1[x]) || isNaN(aIp2[x])
|| aIp1[x] < 0 || aIp1[x] > 255
|| aIp2[x] < 0 || aIp2[x] > 255
) {
return "Invalid IPs: incorrect values";
}
// Calculate weighted difference for each octet
diff += (aIp1[x] - aIp2[x]) * Math.pow(256, (3-x));
}
return Math.abs(diff);
};
console.log(countIp(ip1, ip2));
246
Step-by-Step Calculation
const explainCalculation = (ip1, ip2) => {
const aIp1 = ip1.split(".").map(Number);
const aIp2 = ip2.split(".").map(Number);
console.log(`IP1: ${ip1} ? [${aIp1.join(', ')}]`);
console.log(`IP2: ${ip2} ? [${aIp2.join(', ')}]`);
let decimal1 = 0, decimal2 = 0;
for (let i = 0; i < 4; i++) {
const weight = Math.pow(256, 3-i);
decimal1 += aIp1[i] * weight;
decimal2 += aIp2[i] * weight;
console.log(`Octet ${i+1}: ${aIp1[i]} vs ${aIp2[i]} (weight: ${weight})`);
}
console.log(`Decimal1: ${decimal1}`);
console.log(`Decimal2: ${decimal2}`);
console.log(`Difference: ${Math.abs(decimal1 - decimal2)}`);
};
explainCalculation('20.0.0.10', '20.0.1.0');
IP1: 20.0.0.10 ? [20, 0, 0, 10] IP2: 20.0.1.0 ? [20, 0, 1, 0] Octet 1: 20 vs 20 (weight: 16777216) Octet 2: 0 vs 0 (weight: 65536) Octet 3: 0 vs 1 (weight: 256) Octet 4: 10 vs 0 (weight: 1) Decimal1: 335544330 Decimal2: 335544576 Difference: 246
Enhanced Version with Better Error Handling
const countIPAddresses = (startIP, endIP) => {
const ipToDecimal = (ip) => {
const octets = ip.split('.');
if (octets.length !== 4) {
throw new Error('Invalid IP format');
}
return octets.reduce((decimal, octet, index) => {
const num = parseInt(octet, 10);
if (isNaN(num) || num < 0 || num > 255) {
throw new Error(`Invalid octet: ${octet}`);
}
return decimal + num * Math.pow(256, 3 - index);
}, 0);
};
try {
const start = ipToDecimal(startIP);
const end = ipToDecimal(endIP);
return Math.abs(end - start);
} catch (error) {
return `Error: ${error.message}`;
}
};
// Test cases
console.log(countIPAddresses('192.168.1.1', '192.168.1.10'));
console.log(countIPAddresses('10.0.0.0', '10.0.1.0'));
console.log(countIPAddresses('invalid.ip', '192.168.1.1'));
9 256 Error: Invalid octet: invalid
Key Points
- IPv4 addresses are converted to 32-bit decimal numbers for calculation
- Each octet contributes with weights: 256³, 256², 256¹, 256?
- The function includes validation for proper IP format and range (0-255)
- Result excludes the ending IP address as specified
Conclusion
This approach efficiently counts IP addresses by converting IPv4 addresses to decimal format and calculating their difference. The method handles validation and provides accurate results for network address counting.
Advertisements
