c# - Generate IP which lie in between start and end values of IPv6 -
i needed generate ip(s) lie in between given start , end ip in case of ipv6.
for example start ip 2001:db8:85a3:42:1000:8a2e:370:7334
, end ip 2001:db8:85a3:42:1000:8a2e:370:7336.
i need ip lie in between.
regards
you could:
public static ienumerable<ipaddress> fromto(ipaddress from, ipaddress to) { if (from == null || == null) { throw new argumentnullexception(from == null ? "from" : "to"); } if (from.addressfamily != to.addressfamily) { throw new argumentexception("from/to"); } long scopeid; // scopeid can used ipv6 if (from.addressfamily == addressfamily.internetworkv6) { if (from.scopeid != to.scopeid) { throw new argumentexception("from/to"); } scopeid = from.scopeid; } else { scopeid = 0; } byte[] bytesfrom = from.getaddressbytes(); byte[] bytesto = to.getaddressbytes(); while (true) { int cmp = compare(bytesfrom, bytesto); if (cmp > 0) { break; } if (scopeid != 0) { // constructor can used ipv6 yield return new ipaddress(bytesfrom, scopeid); } else { yield return new ipaddress(bytesfrom); } // second check handle case 255.255.255.255-255.255.255.255 if (cmp == 0) { break; } increment(bytesfrom); } } private static int compare(byte[] x, byte[] y) { (int = 0; < x.length; i++) { int ret = x[i].compareto(y[i]); if (ret != 0) { return ret; } } return 0; } private static void increment(byte[] x) { (int = x.length - 1; >= 0; i--) { if (x[i] != 0xff) { x[i]++; return; } x[i] = 0; } }
and then:
var addr1 = ipaddress.parse("2001:db8:85a3:42:1000:8a2e:370:7334"); var addr2 = ipaddress.parse("2001:db8:85a3:42:1000:8a2e:371:7336"); foreach (ipaddress addr in fromto(addr1, addr2)) { console.writeline(addr); }
note that, written, code compatible both ipv4, ipv6 , ipv6 scope id (like 2001:db8:85a3:42:1000:8a2e:370:7334%100
)
Comments
Post a Comment