using System; using System.Linq; using System.Net; using System.Net.Sockets; namespace Unosquare.Swan { /// /// Provides various extension methods for networking-related tasks. /// public static class NetworkExtensions { /// /// Determines whether the IP address is private. /// /// The IP address. /// /// True if the IP Address is private; otherwise, false. /// /// address. public static Boolean IsPrivateAddress(this IPAddress address) { if(address == null) { throw new ArgumentNullException(nameof(address)); } Byte[] octets = address.ToString().Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(Byte.Parse).ToArray(); Boolean is24Bit = octets[0] == 10; Boolean is20Bit = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31; Boolean is16Bit = octets[0] == 192 && octets[1] == 168; return is24Bit || is20Bit || is16Bit; } /// /// Converts an IPv4 Address to its Unsigned, 32-bit integer representation. /// /// The address. /// /// A 32-bit unsigned integer converted from four bytes at a specified position in a byte array. /// /// address. /// InterNetwork - address. public static UInt32 ToUInt32(this IPAddress address) { if(address == null) { throw new ArgumentNullException(nameof(address)); } if(address.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException($"Address has to be of family '{nameof(AddressFamily.InterNetwork)}'", nameof(address)); } Byte[] addressBytes = address.GetAddressBytes(); if(BitConverter.IsLittleEndian) { Array.Reverse(addressBytes); } return BitConverter.ToUInt32(addressBytes, 0); } } }