简体   繁体   中英

Generate IP range from Start of IP address and count of IP Addresses

So I have seen plenty of examples out on the web that shows how to get the full range of IP's if you know the start IP and the End IP but what I need is is something telling me the full IP range after providing the code with the Start IP and the Number of IP addresses needed.

So for example if I provide the IP address of 192.168.0.1 as the starting IP and the number of IP's needed of 60 IP's, the results should come back with a result of

StartIP = 192.168.0.1
EndIP = 192.168.0.61
IPCount = 60

I have seen the IPNetwork library but that requires the use of CIDR which we are not using.

EDIT:

What I have tried is the following.

I have tried IPNetwork which when using that it is requiring CIDR as stated above we are not using CIDR so that is of no good to me.

I thought of the very basics of just take the last octet and add to that number, so if the last octet is 2 and the number of IP's are 60 than the new last octet is 62. Pretty simple for that but when the last octet is something like 200 and the number of IP's that are needed is 70 than we can't just add to that last octet because that would end you up with 270 for a last octet and since you cannot go over 255 there is an issue. Now how to calculate what that IP should actually be is another issue. I as far as what code have I tried, nothing that is of much use on here because it has showed to be completely the wrong direction to go since I have discovered the problems that I noted above. I'm not looking for someone to straight up write the code for me I can write my own code but what I am hoping for is for someone to get me on the right track to move forward with this. Unfortunately I have never been one for IP addresses. I spent a very short time in School to learn how to calculate IP addresses. That was 14 years ago and only for a small part of a semester.

You can parse the IP address to a 32 bit value (as that's what it really represents), then you can easily loop through a range and create IP addresses for them.

Conversion:

public static uint ParseIP(string ip) {
  byte[] b = ip.Split('.').Select(s => Byte.Parse(s)).ToArray();
  if (BitConverter.IsLittleEndian) Array.Reverse(b);
  return BitConverter.ToUInt32(b, 0);
}

public static string FormatIP(uint ip) {
  byte[] b = BitConverter.GetBytes(ip);
  if (BitConverter.IsLittleEndian) Array.Reverse(b);
  return String.Join(".", b.Select(n => n.ToString()));
}

Creating a range:

string StartIP = "192.168.0.1";
int IPCount = 61;

uint n = ParseIP("192.168.0.1");
string[] range = new string[IPCount];
for (uint i = 0; i < IPCount; i++) {
  range[i] = FormatIP(n + i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM