3

I want to calculate number of number of IP addresses from 2 given IP addresses.

Example: 127.0.1.10 and 127.0.0.200 is 67 IP addresses..

What's easy way of doing this?

NewHelpNeeder
  • 693
  • 1
  • 10
  • 19
  • 2
    It's difficult, since 255 or 0 might need special treatment depending on the size of the subnet. If you don't care about giving those addresses special treatment, you can simply convert to int and substract(and add one if you want both ends to be inclusive). – CodesInChaos Jan 27 '12 at 11:05
  • 6
    Convert both to integers, then subtract! (you have to consider network and broadcast addresses) – Aziz Jan 27 '12 at 11:06
  • As [this answer](http://stackoverflow.com/a/9032408/594137) points out, the answer is very different if the IPs are not on the same subnet. I would suggest clarifying this in your question. – Samuel Harmer Jan 27 '12 at 11:13

2 Answers2

6
int IPToInt(string IP)
{
    return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(IP).GetAddressBytes(), 0));
}

int num = IPToInt("127.0.1.10") - IPToInt("127.0.0.200") + 1; 
L.B
  • 114,136
  • 19
  • 178
  • 224
3

To calculate the amount of IP addresses in a range, or subnet, you need the subnet mask. From this you can know what part of the IP is for the network and which is the hosts. The hosts part will tell you how many hosts are possible within the subnet. The subnet mask was specifically designed so that hardware/software can tell the different what the network part of the IP is, and what the host part of it is.

Without it, I doubt you can know anything.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415