Getting IP address list between two IP addresses

2019-09-18 03:08发布

问题:

I am writing a program that gets From IP address and To IP address from the user and displays the list of IP addresses between them. For example, if the user gives 10.0.0.1 and 10.0.0.5 then I will display the five IP addresses between these two. The current solution that is coming in my mind are:

  1. To have a list of all IP addresses and then look for the resultant IP address list
  2. Use a nested loop

What solution should I adopt between these (or suggest a better solution)? For the first solution, what is the link for IP address table/list?

What is the solution in terms of JavaScript or Java?

回答1:

First split the IP addresses with .. From the first IP address, start increasing the fourth part up to 255 and then add 1 to the third part and set the fourth one to 1. Until you reach the to IP address.

  • IP address bytes -> bits -> Int32
  • From: 10.0.10.10 -> 00001010 00000000 00001010 00001010 -> 167774730
  • To: 10.1.45.1 -> 00001010 00000001 00101101 00000001 -> 167849217
  • Start count from From to To and just check the unwanted bytes which is 11111111 and 00000000.

That's all.



回答2:

The "dot"-writing is for humans. For computers, it is one 4-byte-number. So parse it to a number. Then you will get all addresses in the range by simply increasing a number until the bound is reached and format them back for output.



回答3:

I was experimenting in an updated jsFiddle, and finally I came to the solution below. The following code should work for all IP addresses. You have to provide a start and end IP address in hex (since it is easy, I did not write code for it).

var startIp = 0x0A000001,
endIp = 0x0A000F05;

var  temp, list = [],str;
for(var i=startIp ; i <= endIp ; i++){
    temp = (i).toString(16);
    str ='';
    if(temp.length == 7){
        temp = "0"+temp;
    }

    for(var k=temp.length-1; k  >= 0 ; k-=2){
       str = parseInt(temp[k-1] + "" + temp[k], 16) +"." + str ;
    }
    document.write(temp + " " + str+ "<br>");
    list.push(str.substring(0, str.length-1));
}

?


回答4:

Having a list of all IP addresses and then look for the ones you need is overkill. Plus, I'm sure you'll even be able to store that list without having to buy a few extra hard disk drives.

Just use a nested loop and generate the IP addresses you're looking for.



回答5:

If you know enough to get the addresses (from the network or from the file system or user input), you can test the address itself with subtraction and get the number of IP addresses right there.

This is simplified, but you will get it if you know about addresses: 000044-000002 = 000042.