2
0

IPObject.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. namespace MediaBrowser.Common.Net
  5. {
  6. /// <summary>
  7. /// Base network object class.
  8. /// </summary>
  9. public abstract class IPObject : IEquatable<IPObject>
  10. {
  11. /// <summary>
  12. /// The network address of this object.
  13. /// </summary>
  14. private IPObject? _networkAddress;
  15. /// <summary>
  16. /// Gets or sets a user defined value that is associated with this object.
  17. /// </summary>
  18. public int Tag { get; set; }
  19. /// <summary>
  20. /// Gets or sets the object's IP address.
  21. /// </summary>
  22. public abstract IPAddress Address { get; set; }
  23. /// <summary>
  24. /// Gets the object's network address.
  25. /// </summary>
  26. public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress();
  27. /// <summary>
  28. /// Gets or sets the object's IP address.
  29. /// </summary>
  30. public abstract byte PrefixLength { get; set; }
  31. /// <summary>
  32. /// Gets the AddressFamily of this object.
  33. /// </summary>
  34. public AddressFamily AddressFamily
  35. {
  36. get
  37. {
  38. // Keep terms separate as Address performs other functions in inherited objects.
  39. IPAddress address = Address;
  40. return address.Equals(IPAddress.None) ? AddressFamily.Unspecified : address.AddressFamily;
  41. }
  42. }
  43. /// <summary>
  44. /// Returns the network address of an object.
  45. /// </summary>
  46. /// <param name="address">IP Address to convert.</param>
  47. /// <param name="prefixLength">Subnet prefix.</param>
  48. /// <returns>IPAddress.</returns>
  49. public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength)
  50. {
  51. if (address == null)
  52. {
  53. throw new ArgumentNullException(nameof(address));
  54. }
  55. if (address.IsIPv4MappedToIPv6)
  56. {
  57. address = address.MapToIPv4();
  58. }
  59. if (IPAddress.IsLoopback(address))
  60. {
  61. return (address, prefixLength);
  62. }
  63. // An ip address is just a list of bytes, each one representing a segment on the network.
  64. // This separates the IP address into octets and calculates how many octets will need to be altered or set to zero dependant upon the
  65. // prefix length value. eg. /16 on a 4 octet ip4 address (192.168.2.240) will result in the 2 and the 240 being zeroed out.
  66. // Where there is not an exact boundary (eg /23), mod is used to calculate how many bits of this value are to be kept.
  67. // GetAddressBytes
  68. Span<byte> addressBytes = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
  69. address.TryWriteBytes(addressBytes, out _);
  70. int div = prefixLength / 8;
  71. int mod = prefixLength % 8;
  72. if (mod != 0)
  73. {
  74. // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear.
  75. mod = 8 - mod;
  76. // Shift out the bits from the octet that we don't want, by moving right then back left.
  77. addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod);
  78. // Move on the next byte.
  79. div++;
  80. }
  81. // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0)
  82. for (int octet = div; octet < addressBytes.Length; octet++)
  83. {
  84. addressBytes[octet] = 0;
  85. }
  86. // Return the network address for the prefix.
  87. return (new IPAddress(addressBytes), prefixLength);
  88. }
  89. /// <summary>
  90. /// Tests to see if the ip address is an IP6 address.
  91. /// </summary>
  92. /// <param name="address">Value to test.</param>
  93. /// <returns>True if it is.</returns>
  94. public static bool IsIP6(IPAddress address)
  95. {
  96. if (address == null)
  97. {
  98. throw new ArgumentNullException(nameof(address));
  99. }
  100. if (address.IsIPv4MappedToIPv6)
  101. {
  102. address = address.MapToIPv4();
  103. }
  104. return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6);
  105. }
  106. /// <summary>
  107. /// Tests to see if the address in the private address range.
  108. /// </summary>
  109. /// <param name="address">Object to test.</param>
  110. /// <returns>True if it contains a private address.</returns>
  111. public static bool IsPrivateAddressRange(IPAddress address)
  112. {
  113. if (address == null)
  114. {
  115. throw new ArgumentNullException(nameof(address));
  116. }
  117. if (!address.Equals(IPAddress.None))
  118. {
  119. if (address.IsIPv4MappedToIPv6)
  120. {
  121. address = address.MapToIPv4();
  122. }
  123. if (address.AddressFamily == AddressFamily.InterNetwork)
  124. {
  125. // GetAddressBytes
  126. Span<byte> octet = stackalloc byte[4];
  127. address.TryWriteBytes(octet, out _);
  128. return (octet[0] == 10)
  129. || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918
  130. || (octet[0] == 192 && octet[1] == 168) // RFC1918
  131. || (octet[0] == 127); // RFC1122
  132. }
  133. else
  134. {
  135. // GetAddressBytes
  136. Span<byte> octet = stackalloc byte[16];
  137. address.TryWriteBytes(octet, out _);
  138. uint word = (uint)(octet[0] << 8) + octet[1];
  139. return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
  140. || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
  141. }
  142. }
  143. return false;
  144. }
  145. /// <summary>
  146. /// Returns true if the IPAddress contains an IP6 Local link address.
  147. /// </summary>
  148. /// <param name="address">IPAddress object to check.</param>
  149. /// <returns>True if it is a local link address.</returns>
  150. /// <remarks>
  151. /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
  152. /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
  153. /// </remarks>
  154. public static bool IsIPv6LinkLocal(IPAddress address)
  155. {
  156. if (address == null)
  157. {
  158. throw new ArgumentNullException(nameof(address));
  159. }
  160. if (address.IsIPv4MappedToIPv6)
  161. {
  162. address = address.MapToIPv4();
  163. }
  164. if (address.AddressFamily != AddressFamily.InterNetworkV6)
  165. {
  166. return false;
  167. }
  168. // GetAddressBytes
  169. Span<byte> octet = stackalloc byte[16];
  170. address.TryWriteBytes(octet, out _);
  171. uint word = (uint)(octet[0] << 8) + octet[1];
  172. return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
  173. }
  174. /// <summary>
  175. /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
  176. /// </summary>
  177. /// <param name="cidr">Subnet mask in CIDR notation.</param>
  178. /// <param name="family">IPv4 or IPv6 family.</param>
  179. /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
  180. public static IPAddress CidrToMask(byte cidr, AddressFamily family)
  181. {
  182. uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr);
  183. addr = ((addr & 0xff000000) >> 24)
  184. | ((addr & 0x00ff0000) >> 8)
  185. | ((addr & 0x0000ff00) << 8)
  186. | ((addr & 0x000000ff) << 24);
  187. return new IPAddress(addr);
  188. }
  189. /// <summary>
  190. /// Convert a mask to a CIDR. IPv4 only.
  191. /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
  192. /// </summary>
  193. /// <param name="mask">Subnet mask.</param>
  194. /// <returns>Byte CIDR representing the mask.</returns>
  195. public static byte MaskToCidr(IPAddress mask)
  196. {
  197. if (mask == null)
  198. {
  199. throw new ArgumentNullException(nameof(mask));
  200. }
  201. byte cidrnet = 0;
  202. if (!mask.Equals(IPAddress.Any))
  203. {
  204. // GetAddressBytes
  205. Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
  206. mask.TryWriteBytes(bytes, out _);
  207. var zeroed = false;
  208. for (var i = 0; i < bytes.Length; i++)
  209. {
  210. for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
  211. {
  212. if (zeroed)
  213. {
  214. // Invalid netmask.
  215. return (byte)~cidrnet;
  216. }
  217. if ((v & 0x80) == 0)
  218. {
  219. zeroed = true;
  220. }
  221. else
  222. {
  223. cidrnet++;
  224. }
  225. }
  226. }
  227. }
  228. return cidrnet;
  229. }
  230. /// <summary>
  231. /// Tests to see if this object is a Loopback address.
  232. /// </summary>
  233. /// <returns>True if it is.</returns>
  234. public virtual bool IsLoopback()
  235. {
  236. return IPAddress.IsLoopback(Address);
  237. }
  238. /// <summary>
  239. /// Removes all addresses of a specific type from this object.
  240. /// </summary>
  241. /// <param name="family">Type of address to remove.</param>
  242. public virtual void Remove(AddressFamily family)
  243. {
  244. // This method only performs a function in the IPHost implementation of IPObject.
  245. }
  246. /// <summary>
  247. /// Tests to see if this object is an IPv6 address.
  248. /// </summary>
  249. /// <returns>True if it is.</returns>
  250. public virtual bool IsIP6()
  251. {
  252. return IsIP6(Address);
  253. }
  254. /// <summary>
  255. /// Returns true if this IP address is in the RFC private address range.
  256. /// </summary>
  257. /// <returns>True this object has a private address.</returns>
  258. public virtual bool IsPrivateAddressRange()
  259. {
  260. return IsPrivateAddressRange(Address);
  261. }
  262. /// <summary>
  263. /// Compares this to the object passed as a parameter.
  264. /// </summary>
  265. /// <param name="ip">Object to compare to.</param>
  266. /// <returns>Equality result.</returns>
  267. public virtual bool Equals(IPAddress ip)
  268. {
  269. if (ip != null)
  270. {
  271. if (ip.IsIPv4MappedToIPv6)
  272. {
  273. ip = ip.MapToIPv4();
  274. }
  275. return !Address.Equals(IPAddress.None) && Address.Equals(ip);
  276. }
  277. return false;
  278. }
  279. /// <summary>
  280. /// Compares this to the object passed as a parameter.
  281. /// </summary>
  282. /// <param name="other">Object to compare to.</param>
  283. /// <returns>Equality result.</returns>
  284. public virtual bool Equals(IPObject? other)
  285. {
  286. if (other != null)
  287. {
  288. return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
  289. }
  290. return false;
  291. }
  292. /// <summary>
  293. /// Compares the address in this object and the address in the object passed as a parameter.
  294. /// </summary>
  295. /// <param name="address">Object's IP address to compare to.</param>
  296. /// <returns>Comparison result.</returns>
  297. public abstract bool Contains(IPObject address);
  298. /// <summary>
  299. /// Compares the address in this object and the address in the object passed as a parameter.
  300. /// </summary>
  301. /// <param name="address">Object's IP address to compare to.</param>
  302. /// <returns>Comparison result.</returns>
  303. public abstract bool Contains(IPAddress address);
  304. /// <inheritdoc/>
  305. public override int GetHashCode()
  306. {
  307. return Address.GetHashCode();
  308. }
  309. /// <inheritdoc/>
  310. public override bool Equals(object? obj)
  311. {
  312. return Equals(obj as IPObject);
  313. }
  314. /// <summary>
  315. /// Calculates the network address of this object.
  316. /// </summary>
  317. /// <returns>Returns the network address of this object.</returns>
  318. protected abstract IPObject CalculateNetworkAddress();
  319. }
  320. }