IPObject.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. byte[] addressBytes = address.GetAddressBytes();
  77. int div = prefixLength / 8;
  78. int mod = prefixLength % 8;
  79. if (mod != 0)
  80. {
  81. // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear.
  82. mod = 8 - mod;
  83. // Shift out the bits from the octet that we don't want, by moving right then back left.
  84. addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod);
  85. // Move on the next byte.
  86. div++;
  87. }
  88. // 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)
  89. for (int octet = div; octet < addressBytes.Length; octet++)
  90. {
  91. addressBytes[octet] = 0;
  92. }
  93. // Return the network address for the prefix.
  94. return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength);
  95. }
  96. /// <summary>
  97. /// Tests to see if the ip address is a Loopback address.
  98. /// </summary>
  99. /// <param name="address">Value to test.</param>
  100. /// <returns>True if it is.</returns>
  101. public static bool IsLoopback(IPAddress address)
  102. {
  103. if (address == null)
  104. {
  105. throw new ArgumentNullException(nameof(address));
  106. }
  107. if (!address.Equals(IPAddress.None))
  108. {
  109. if (address.IsIPv4MappedToIPv6)
  110. {
  111. address = address.MapToIPv4();
  112. }
  113. return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback);
  114. }
  115. return false;
  116. }
  117. /// <summary>
  118. /// Tests to see if the ip address is an IP6 address.
  119. /// </summary>
  120. /// <param name="address">Value to test.</param>
  121. /// <returns>True if it is.</returns>
  122. public static bool IsIP6(IPAddress address)
  123. {
  124. if (address == null)
  125. {
  126. throw new ArgumentNullException(nameof(address));
  127. }
  128. if (address.IsIPv4MappedToIPv6)
  129. {
  130. address = address.MapToIPv4();
  131. }
  132. return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6);
  133. }
  134. /// <summary>
  135. /// Tests to see if the address in the private address range.
  136. /// </summary>
  137. /// <param name="address">Object to test.</param>
  138. /// <returns>True if it contains a private address.</returns>
  139. public static bool IsPrivateAddressRange(IPAddress address)
  140. {
  141. if (address == null)
  142. {
  143. throw new ArgumentNullException(nameof(address));
  144. }
  145. if (!address.Equals(IPAddress.None))
  146. {
  147. if (address.AddressFamily == AddressFamily.InterNetwork)
  148. {
  149. if (address.IsIPv4MappedToIPv6)
  150. {
  151. address = address.MapToIPv4();
  152. }
  153. byte[] octet = address.GetAddressBytes();
  154. return (octet[0] == 10)
  155. || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918
  156. || (octet[0] == 192 && octet[1] == 168) // RFC1918
  157. || (octet[0] == 127); // RFC1122
  158. }
  159. else
  160. {
  161. byte[] octet = address.GetAddressBytes();
  162. uint word = (uint)(octet[0] << 8) + octet[1];
  163. return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
  164. || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
  165. }
  166. }
  167. return false;
  168. }
  169. /// <summary>
  170. /// Returns true if the IPAddress contains an IP6 Local link address.
  171. /// </summary>
  172. /// <param name="address">IPAddress object to check.</param>
  173. /// <returns>True if it is a local link address.</returns>
  174. /// <remarks>
  175. /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
  176. /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
  177. /// </remarks>
  178. public static bool IsIPv6LinkLocal(IPAddress address)
  179. {
  180. if (address == null)
  181. {
  182. throw new ArgumentNullException(nameof(address));
  183. }
  184. if (address.IsIPv4MappedToIPv6)
  185. {
  186. address = address.MapToIPv4();
  187. }
  188. if (address.AddressFamily != AddressFamily.InterNetworkV6)
  189. {
  190. return false;
  191. }
  192. byte[] octet = address.GetAddressBytes();
  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. byte[] bytes = mask.GetAddressBytes();
  227. var zeroed = false;
  228. for (var i = 0; i < bytes.Length; i++)
  229. {
  230. for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
  231. {
  232. if (zeroed)
  233. {
  234. // Invalid netmask.
  235. return (byte)~cidrnet;
  236. }
  237. if ((v & 0x80) == 0)
  238. {
  239. zeroed = true;
  240. }
  241. else
  242. {
  243. cidrnet++;
  244. }
  245. }
  246. }
  247. }
  248. return cidrnet;
  249. }
  250. /// <summary>
  251. /// Tests to see if this object is a Loopback address.
  252. /// </summary>
  253. /// <returns>True if it is.</returns>
  254. public virtual bool IsLoopback()
  255. {
  256. return IsLoopback(Address);
  257. }
  258. /// <summary>
  259. /// Removes all addresses of a specific type from this object.
  260. /// </summary>
  261. /// <param name="family">Type of address to remove.</param>
  262. public virtual void Remove(AddressFamily family)
  263. {
  264. // This method only performs a function in the IPHost implementation of IPObject.
  265. }
  266. /// <summary>
  267. /// Tests to see if this object is an IPv6 address.
  268. /// </summary>
  269. /// <returns>True if it is.</returns>
  270. public virtual bool IsIP6()
  271. {
  272. return IsIP6(Address);
  273. }
  274. /// <summary>
  275. /// Returns true if this IP address is in the RFC private address range.
  276. /// </summary>
  277. /// <returns>True this object has a private address.</returns>
  278. public virtual bool IsPrivateAddressRange()
  279. {
  280. return IsPrivateAddressRange(Address);
  281. }
  282. /// <summary>
  283. /// Compares this to the object passed as a parameter.
  284. /// </summary>
  285. /// <param name="ip">Object to compare to.</param>
  286. /// <returns>Equality result.</returns>
  287. public virtual bool Equals(IPAddress ip)
  288. {
  289. if (ip != null)
  290. {
  291. if (ip.IsIPv4MappedToIPv6)
  292. {
  293. ip = ip.MapToIPv4();
  294. }
  295. return !Address.Equals(IPAddress.None) && Address.Equals(ip);
  296. }
  297. return false;
  298. }
  299. /// <summary>
  300. /// Compares this to the object passed as a parameter.
  301. /// </summary>
  302. /// <param name="other">Object to compare to.</param>
  303. /// <returns>Equality result.</returns>
  304. public virtual bool Equals(IPObject? other)
  305. {
  306. if (other != null)
  307. {
  308. return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
  309. }
  310. return false;
  311. }
  312. /// <summary>
  313. /// Compares the address in this object and the address in the object passed as a parameter.
  314. /// </summary>
  315. /// <param name="address">Object's IP address to compare to.</param>
  316. /// <returns>Comparison result.</returns>
  317. public abstract bool Contains(IPObject address);
  318. /// <summary>
  319. /// Compares the address in this object and the address in the object passed as a parameter.
  320. /// </summary>
  321. /// <param name="address">Object's IP address to compare to.</param>
  322. /// <returns>Comparison result.</returns>
  323. public abstract bool Contains(IPAddress address);
  324. /// <inheritdoc/>
  325. public override int GetHashCode()
  326. {
  327. return Address.GetHashCode();
  328. }
  329. /// <inheritdoc/>
  330. public override bool Equals(object? obj)
  331. {
  332. return Equals(obj as IPObject);
  333. }
  334. /// <summary>
  335. /// Calculates the network address of this object.
  336. /// </summary>
  337. /// <returns>Returns the network address of this object.</returns>
  338. protected abstract IPObject CalculateNetworkAddress();
  339. }
  340. }