NetworkHelpers.cs 2.4 KB

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