IPObject.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 (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 a Loopback address.
  91. /// </summary>
  92. /// <param name="address">Value to test.</param>
  93. /// <returns>True if it is.</returns>
  94. public static bool IsLoopback(IPAddress address)
  95. {
  96. if (address == null)
  97. {
  98. throw new ArgumentNullException(nameof(address));
  99. }
  100. if (!address.Equals(IPAddress.None))
  101. {
  102. if (address.IsIPv4MappedToIPv6)
  103. {
  104. address = address.MapToIPv4();
  105. }
  106. return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback);
  107. }
  108. return false;
  109. }
  110. /// <summary>
  111. /// Tests to see if the ip address is an IP6 address.
  112. /// </summary>
  113. /// <param name="address">Value to test.</param>
  114. /// <returns>True if it is.</returns>
  115. public static bool IsIP6(IPAddress address)
  116. {
  117. if (address == null)
  118. {
  119. throw new ArgumentNullException(nameof(address));
  120. }
  121. if (address.IsIPv4MappedToIPv6)
  122. {
  123. address = address.MapToIPv4();
  124. }
  125. return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6);
  126. }
  127. /// <summary>
  128. /// Tests to see if the address in the private address range.
  129. /// </summary>
  130. /// <param name="address">Object to test.</param>
  131. /// <returns>True if it contains a private address.</returns>
  132. public static bool IsPrivateAddressRange(IPAddress address)
  133. {
  134. if (address == null)
  135. {
  136. throw new ArgumentNullException(nameof(address));
  137. }
  138. if (!address.Equals(IPAddress.None))
  139. {
  140. if (address.IsIPv4MappedToIPv6)
  141. {
  142. address = address.MapToIPv4();
  143. }
  144. if (address.AddressFamily == AddressFamily.InterNetwork)
  145. {
  146. // GetAddressBytes
  147. Span<byte> octet = stackalloc byte[4];
  148. address.TryWriteBytes(octet, out _);
  149. return (octet[0] == 10)
  150. || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918
  151. || (octet[0] == 192 && octet[1] == 168) // RFC1918
  152. || (octet[0] == 127); // RFC1122
  153. }
  154. else
  155. {
  156. // GetAddressBytes
  157. Span<byte> octet = stackalloc byte[16];
  158. address.TryWriteBytes(octet, out _);
  159. uint word = (uint)(octet[0] << 8) + octet[1];
  160. return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
  161. || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
  162. }
  163. }
  164. return false;
  165. }
  166. /// <summary>
  167. /// Returns true if the IPAddress contains an IP6 Local link address.
  168. /// </summary>
  169. /// <param name="address">IPAddress object to check.</param>
  170. /// <returns>True if it is a local link address.</returns>
  171. /// <remarks>
  172. /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
  173. /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
  174. /// </remarks>
  175. public static bool IsIPv6LinkLocal(IPAddress address)
  176. {
  177. if (address == null)
  178. {
  179. throw new ArgumentNullException(nameof(address));
  180. }
  181. if (address.IsIPv4MappedToIPv6)
  182. {
  183. address = address.MapToIPv4();
  184. }
  185. if (address.AddressFamily != AddressFamily.InterNetworkV6)
  186. {
  187. return false;
  188. }
  189. // GetAddressBytes
  190. Span<byte> octet = stackalloc byte[16];
  191. address.TryWriteBytes(octet, out _);
  192. uint word = (uint)(octet[0] << 8) + octet[1];
  193. return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
  194. }
  195. /// <summary>
  196. /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
  197. /// </summary>
  198. /// <param name="cidr">Subnet mask in CIDR notation.</param>
  199. /// <param name="family">IPv4 or IPv6 family.</param>
  200. /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
  201. public static IPAddress CidrToMask(byte cidr, AddressFamily family)
  202. {
  203. uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr);
  204. addr = ((addr & 0xff000000) >> 24)
  205. | ((addr & 0x00ff0000) >> 8)
  206. | ((addr & 0x0000ff00) << 8)
  207. | ((addr & 0x000000ff) << 24);
  208. return new IPAddress(addr);
  209. }
  210. /// <summary>
  211. /// Convert a mask to a CIDR. IPv4 only.
  212. /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
  213. /// </summary>
  214. /// <param name="mask">Subnet mask.</param>
  215. /// <returns>Byte CIDR representing the mask.</returns>
  216. public static byte MaskToCidr(IPAddress mask)
  217. {
  218. if (mask == null)
  219. {
  220. throw new ArgumentNullException(nameof(mask));
  221. }
  222. byte cidrnet = 0;
  223. if (!mask.Equals(IPAddress.Any))
  224. {
  225. // GetAddressBytes
  226. Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
  227. mask.TryWriteBytes(bytes, out _);
  228. var zeroed = false;
  229. for (var i = 0; i < bytes.Length; i++)
  230. {
  231. for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
  232. {
  233. if (zeroed)
  234. {
  235. // Invalid netmask.
  236. return (byte)~cidrnet;
  237. }
  238. if ((v & 0x80) == 0)
  239. {
  240. zeroed = true;
  241. }
  242. else
  243. {
  244. cidrnet++;
  245. }
  246. }
  247. }
  248. }
  249. return cidrnet;
  250. }
  251. /// <summary>
  252. /// Tests to see if this object is a Loopback address.
  253. /// </summary>
  254. /// <returns>True if it is.</returns>
  255. public virtual bool IsLoopback()
  256. {
  257. return IsLoopback(Address);
  258. }
  259. /// <summary>
  260. /// Removes all addresses of a specific type from this object.
  261. /// </summary>
  262. /// <param name="family">Type of address to remove.</param>
  263. public virtual void Remove(AddressFamily family)
  264. {
  265. // This method only performs a function in the IPHost implementation of IPObject.
  266. }
  267. /// <summary>
  268. /// Tests to see if this object is an IPv6 address.
  269. /// </summary>
  270. /// <returns>True if it is.</returns>
  271. public virtual bool IsIP6()
  272. {
  273. return IsIP6(Address);
  274. }
  275. /// <summary>
  276. /// Returns true if this IP address is in the RFC private address range.
  277. /// </summary>
  278. /// <returns>True this object has a private address.</returns>
  279. public virtual bool IsPrivateAddressRange()
  280. {
  281. return IsPrivateAddressRange(Address);
  282. }
  283. /// <summary>
  284. /// Compares this to the object passed as a parameter.
  285. /// </summary>
  286. /// <param name="ip">Object to compare to.</param>
  287. /// <returns>Equality result.</returns>
  288. public virtual bool Equals(IPAddress ip)
  289. {
  290. if (ip != null)
  291. {
  292. if (ip.IsIPv4MappedToIPv6)
  293. {
  294. ip = ip.MapToIPv4();
  295. }
  296. return !Address.Equals(IPAddress.None) && Address.Equals(ip);
  297. }
  298. return false;
  299. }
  300. /// <summary>
  301. /// Compares this to the object passed as a parameter.
  302. /// </summary>
  303. /// <param name="other">Object to compare to.</param>
  304. /// <returns>Equality result.</returns>
  305. public virtual bool Equals(IPObject? other)
  306. {
  307. if (other != null)
  308. {
  309. return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
  310. }
  311. return false;
  312. }
  313. /// <summary>
  314. /// Compares the address in this object and the address in the object passed as a parameter.
  315. /// </summary>
  316. /// <param name="address">Object's IP address to compare to.</param>
  317. /// <returns>Comparison result.</returns>
  318. public abstract bool Contains(IPObject address);
  319. /// <summary>
  320. /// Compares the address in this object and the address in the object passed as a parameter.
  321. /// </summary>
  322. /// <param name="address">Object's IP address to compare to.</param>
  323. /// <returns>Comparison result.</returns>
  324. public abstract bool Contains(IPAddress address);
  325. /// <inheritdoc/>
  326. public override int GetHashCode()
  327. {
  328. return Address.GetHashCode();
  329. }
  330. /// <inheritdoc/>
  331. public override bool Equals(object? obj)
  332. {
  333. return Equals(obj as IPObject);
  334. }
  335. /// <summary>
  336. /// Calculates the network address of this object.
  337. /// </summary>
  338. /// <returns>Returns the network address of this object.</returns>
  339. protected abstract IPObject CalculateNetworkAddress();
  340. }
  341. }