![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting the number of IP addresses present between two IP addresses in JavaScript
Problem
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.
Example
Following is the code −
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("."); if (aIp1.length !== 4 || aIp2.length !== 4) { return "Invalid IPs: incorrect format"; } for (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" } diff += (aIp1[x] - aIp2[x]) * (256 * (3-x)); } return Math.abs(diff); }; console.log(countIp(ip1, ip2));
Output
Following is the console output −
256
Advertisements