Created
December 7, 2013 17:37
-
-
Save adrianstevens/7845866 to your computer and use it in GitHub Desktop.
http://stackoverflow.com/questions/7082727/calculating-all-addresses-within-a-subnet-for-ipv6 IPV6 example from StackOverflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string strIn = "2001:DB8::/120"; | |
//Split the string in parts for address and prefix | |
string strAddress = strIn.Substring(0, strIn.IndexOf('/')); | |
string strPrefix = strIn.Substring(strIn.IndexOf('/') + 1); | |
int iPrefix = Int32.Parse(strPrefix); | |
IPAddress ipAddress = IPAddress.Parse(strAddress); | |
//Convert the prefix length to a valid SubnetMask | |
int iMaskLength = 32; | |
if(ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) | |
{ | |
iMaskLength = 128; | |
} | |
BitArray btArray = new BitArray(iMaskLength); | |
for (int iC1 = 0; iC1 < iMaskLength; iC1++) | |
{ | |
//Index calculation is a bit strange, since you have to make your mind about byte order. | |
int iIndex = (int)((iMaskLength - iC1 - 1) / 8) * 8 + (iC1 % 8); | |
if (iC1 < (iMaskLength - iPrefix)) | |
{ | |
btArray.Set(iIndex, false); | |
} | |
else | |
{ | |
btArray.Set(iIndex, true); | |
} | |
} | |
byte[] bMaskData = new byte[iMaskLength / 8]; | |
btArray.CopyTo(bMaskData, 0); | |
//Create subnetmask | |
Subnetmask smMask = new Subnetmask(bMaskData); | |
//Get the IP range | |
IPAddress ipaStart = IPAddressAnalysis.GetClasslessNetworkAddress(ipAddress, smMask); | |
IPAddress ipaEnd = IPAddressAnalysis.GetClasslessBroadcastAddress(ipAddress, smMask); | |
//Omit the following lines if your network range is large | |
IPAddress[] ipaRange = IPAddressAnalysis.GetIPRange(ipaStart, ipaEnd); | |
//Debug output | |
foreach (IPAddress ipa in ipaRange) | |
{ | |
Console.WriteLine(ipa.ToString()); | |
} | |
Console.ReadLine(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment