IPObject.cs 14 KB

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