Created
November 28, 2017 12:15
-
-
Save JKamsker/c4f34a5cb18a8a290fbb4891516f6983 to your computer and use it in GitHub Desktop.
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
| //+ IPv4Mask {255.255.255.0} System.Net.IPAddress | |
| //+ Address {10.0.0.6} System.Net.IPAddress | |
| /// <summary> | |
| /// Get all IPAdresses which are in the current subnet | |
| /// </summary> | |
| /// <returns></returns> | |
| public static List<IPAddress> GetAllIp() | |
| { | |
| var retVar = new List<IPAddress>(); | |
| //Gather all networkinterface information required | |
| var interfaceInfos = NetworkInterface.GetAllNetworkInterfaces() | |
| .Where(m => m.NetworkInterfaceType != NetworkInterfaceType.Loopback && m.OperationalStatus == OperationalStatus.Up) | |
| .SelectMany(m => m.GetIPProperties().UnicastAddresses) | |
| .Where(m => m.Address.AddressFamily == AddressFamily.InterNetwork); | |
| //Fill all ip ranges | |
| foreach (var interfaceInfo in interfaceInfos) | |
| { | |
| byte[] mask = interfaceInfo.IPv4Mask.GetAddressBytes(); | |
| byte[] netid = BitConverter.GetBytes(BitConverter.ToUInt32(interfaceInfo.Address.GetAddressBytes(), 0) & BitConverter.ToUInt32(mask, 0)); | |
| retVar.AddRange(GetIpRange(netid, BitConverter.GetBytes(BitConverter.ToUInt32(netid, 0) ^ BitConverter.ToUInt32(mask.Select(r => (byte)(byte.MaxValue - r)).ToArray(), 0)))); | |
| } | |
| return retVar; | |
| } | |
| /// <summary> | |
| /// Calculate all ips between the two ones | |
| /// </summary> | |
| /// <param name="ip1"></param> | |
| /// <param name="ip2"></param> | |
| /// <returns></returns> | |
| private static List<IPAddress> GetIpRange(byte[] ip1, byte[] ip2) | |
| { | |
| var retVar = new List<IPAddress>(); | |
| UInt32 bMax = BitConverter.ToUInt32(ip2.Reverse().ToArray(), 0) - 1; | |
| for (UInt32 n = BitConverter.ToUInt32(ip1.Reverse().ToArray(), 0) + 1; n <= bMax; n++) | |
| retVar.Add(new IPAddress(BitConverter.GetBytes(n).Reverse().ToArray())); | |
| return retVar; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment