IPObject.cs 14 KB

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