constipsBetween=(ip1,ip2)=>{letdiff=0;constaIp1=ip1.split(".");constaIp2=ip2.split(".");// check that the IPs are well formedif(aIp1.length!==4||aIp2.length!==4){return"Invalid IPs: incorrect format";}for(x=0;x<4;x++){// check that all the parts are valid (numeric and 0-255)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));}returnMath.abs(diff);}
A bit verbose, but it seems to work fine. Live demo on CodePen.
Perl, using recursion. Tests included. It throws an exception if the end address precedes the start one.
#!/usr/bin/perlusewarnings;usestrict;sub _ips_between{my($list1,$list2,$sum)=@_;return$sumunless@$list1;my($e1,$e2)=(shift@$list1,shift@$list2);die"End before start.\n"if$e2<$e1&&$sum==0;return_ips_between($list1,$list2,$sum+($e2-$e1)*256**@$list1)}sub ips_between{_ips_between([split/\./,shift],[split/\./,shift],0)}useTest::Moretests=>6;useTest::Exception;isips_between('10.0.0.0','10.0.0.50'),50;isips_between('10.0.0.0','10.0.1.0'),256;isips_between('20.0.0.10','20.0.1.0'),246;isips_between('0.255.127.12','1.2.3.4'),164_856;isips_between('1.1.1.1','1.1.1.1'),0;throws_ok{ips_between('1.1.1.1','1.1.0.1')}qr/End before start/;
19 yo student *and* a full-time developer.
Building with Rails currently, exploring new frontiers.
I enjoy functional programming, Linux, FOSS, refactoring and mentoring :)
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.JavaScript
A bit verbose, but it seems to work fine. Live demo on CodePen.
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:
Elixir:
Python IPv4 and IPv6:
in C#
PHP :D
demo: 3v4l.org/8NiWc