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