Your challenge is to write a function that accepts starting and ending IPv4 addresses and returns the number of IP addresses from start to end, excluding the ending address. All input will be valid IPv4 addresses in the forms of strings.
Examples:
ipsBetween("10.0.0.0", "10.0.0.50") => 50
ipsBetween("10.0.0.0", "10.0.1.0") => 256
ipsBetween("20.0.0.10", "20.0.1.0") => 246
It would be impressive if anyone wanted to try their hand at creating the same function for IPv6. You might have to work with some hefty numbers though.
Good luck, happy coding!
This challenge comes from user xDranik. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (13)
Ruby, and totally cheating by using it's IPAddr class :)
This actually made me chuckle... lol cheating indeed 😁
And it was my first idea as well... IPv4 Addresses are 4byte integers... so the easiest way is to subtract them. 😎
ip2int()
is from Stack Overflow.Here's mine! I extended it a little to work if the start and end were reversed.
Gist: gist.github.com/kerrishotts/797450...
Perl, using recursion. Tests included. It throws an exception if the end address precedes the start one.
Here is the simple solution with Python:
Python IPv4 and IPv6:
Elixir:
JavaScript
A bit verbose, but it seems to work fine. Live demo on CodePen.
in C#