NetworkHelpers.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Buffers.Binary;
  2. using System.Net;
  3. using System.Net.NetworkInformation;
  4. namespace Ryujinx.Common.Utilities
  5. {
  6. public static class NetworkHelpers
  7. {
  8. private static (IPInterfaceProperties, UnicastIPAddressInformation) GetLocalInterface(NetworkInterface adapter, bool isPreferred)
  9. {
  10. IPInterfaceProperties properties = adapter.GetIPProperties();
  11. if (isPreferred || (properties.GatewayAddresses.Count > 0 && properties.DnsAddresses.Count > 0))
  12. {
  13. foreach (UnicastIPAddressInformation info in properties.UnicastAddresses)
  14. {
  15. // Only accept an IPv4 address
  16. if (info.Address.GetAddressBytes().Length == 4)
  17. {
  18. return (properties, info);
  19. }
  20. }
  21. }
  22. return (null, null);
  23. }
  24. public static (IPInterfaceProperties, UnicastIPAddressInformation) GetLocalInterface(string lanInterfaceId = "0")
  25. {
  26. if (!NetworkInterface.GetIsNetworkAvailable())
  27. {
  28. return (null, null);
  29. }
  30. IPInterfaceProperties targetProperties = null;
  31. UnicastIPAddressInformation targetAddressInfo = null;
  32. NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
  33. string guid = lanInterfaceId;
  34. bool hasPreference = guid != "0";
  35. foreach (NetworkInterface adapter in interfaces)
  36. {
  37. bool isPreferred = adapter.Id == guid;
  38. // Ignore loopback and non IPv4 capable interface.
  39. if (isPreferred || (targetProperties == null && adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && adapter.Supports(NetworkInterfaceComponent.IPv4)))
  40. {
  41. (IPInterfaceProperties properties, UnicastIPAddressInformation info) = GetLocalInterface(adapter, isPreferred);
  42. if (properties != null)
  43. {
  44. targetProperties = properties;
  45. targetAddressInfo = info;
  46. if (isPreferred || !hasPreference)
  47. {
  48. break;
  49. }
  50. }
  51. }
  52. }
  53. return (targetProperties, targetAddressInfo);
  54. }
  55. public static uint ConvertIpv4Address(IPAddress ipAddress)
  56. {
  57. return BinaryPrimitives.ReadUInt32BigEndian(ipAddress.GetAddressBytes());
  58. }
  59. public static uint ConvertIpv4Address(string ipAddress)
  60. {
  61. return ConvertIpv4Address(IPAddress.Parse(ipAddress));
  62. }
  63. }
  64. }