IPv6 Address Ranging in C#
I'm writing a socket server that requires the ability to allow/restrict by IP and I'm trying to make it compatible with both IPv4开发者_如何学C and IPv6.
I understand the IPv4 principle fairly well, for example I can allow 192.168.0.0/255.255.255.0 catering for all 192.168.0.* addresses, basing my code off of http://blogs.msdn.com/b/knom/archive/2008/12/31/ip-address-calculations-with-c-subnetmasks-networks.aspx.
However, how does this work with IPv6? i.e how do I handle ranges with that protocol?
IPv6 by convention does not use the subnet mask format like IPv4 does. However, there is no reason why you cannot visualise it that way still.
An equivalent “subnet mask” for /64 in IPv6 would be ffff:ffff:ffff:fffff:0:0:0:0
. Just don’t try quoting that to any IPv6 user, as nobody will know what you mean. And don’t try pasting that into any IPv6 configuration — people only ever use prefixes like /64, /48, /32, etc. (Anything smaller than /64, such as /96, is rarely used, and officially deprecated for LAN environments.)
Here’s a handy ASCII art chart I just wrote up to help you understand IPv6 prefixes:
2001:db8:1000:2000:3000:4000:5000:6000/32
<--net--><-------------------host---->
2001:db8:1000:2000:3000:4000:5000:6000/48
<--network--> <--------------host---->
2001:db8:1000:2000:3000:4000:5000:6000/64
<--network-------> <---------host---->
2001:db8:1000:2000:3000:4000:5000:6000/96
<--network------------> <----host---->
Hopefully the above is the same way you would visualise IPv4 subnets (it’s pretty much exactly the same, to be honest). In fact, calculating IPv6 is slightly easier in your head, because IPv6 uses hexadecimal, so if you stick to prefixes divisible by 4, you get to divide your subnet at the nybble (i.e. digit) boundary — something you can’t do with IPv4!
I acknowledge that my answer does not have any C# specific information in it. Nevertheless, it should put you on the right track with what to look for: specifying the prefix lengths.
精彩评论