2

want to take 198.162.1.1/24 and convert it to 198.162.1.1 - 198.162.1.124` or whatever the equivalent would be. So trying to figure out how to mathematically figure that out with dart.

Example:

Input: 192.168.0.1/25

Result: 192.168.0.1 - 192.168.0.126

mousetail
  • 7,009
  • 4
  • 25
  • 45
rizwika
  • 115
  • 1
  • 8

1 Answers1

1

I ported this answer over to Dart. Since there doesn't seem to be a built-in IP address library for Dart, I had to create ip2int and int2ip. This matches the output of this site.

int ip2int(String ipAddr) {
  final parts = ipAddr.split('.').map((str) => int.parse(str)).toList();

  return (parts[0] << 24) + (parts[1] << 16) + (parts[2] << 8) + (parts[3]);
}

String int2ip(int ipAddr) {
  return [
    (ipAddr >> 24).toString(),
    ((ipAddr & 0xff0000) >> 16).toString(),
    ((ipAddr & 0xff00) >> 8).toString(),
    (ipAddr & 0xff).toString()
  ].join('.');
}

List<String> ipRange(String cidr) {
  final range = ['', ''];
  final cidrSplit = cidr.split('/');

  range[0] =
      int2ip((ip2int(cidrSplit[0])) & ((-1 << (32 - int.parse(cidrSplit[1])))));
  range[1] = int2ip(
      (ip2int(range[0])) + (1 << (32 - int.parse(cidrSplit[1]))).toInt() - 1);

  return range;
}

void main() {
  print(ipRange('198.162.1.1/24'));
  print(ipRange('192.168.0.1/25'));
}

Output:

[198.162.1.0, 198.162.1.255]
[192.168.0.0, 192.168.0.127]
user2233706
  • 6,148
  • 5
  • 44
  • 86