using System; using System.Net.NetworkInformation; using System.Net; using System.Net.Sockets; namespace SBRL.Utilities { public static class NetTools { /// /// case-insensitively gets the IPv4 index of the network interface with the given name. /// /// The interface name to search for. /// The IPv4 index of the network interface with the given name. public static int GetNetworkIndexByName4 (string targetInterfaceName) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { Console.WriteLine("Id: {0}, Description: {1}", nic.Id, nic.Description); if (nic.Id == targetInterfaceName) return nic.GetIPv4Index(); } throw new Exception($"Error: Can't find network interface with the name {targetInterfaceName}."); } /// /// Gets the NetworkInterface with the given IP address. /// /// The target IP to search for. /// The network index with the given IP address. public static int GetNetworkIndexByIP (IPAddress targetIP) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { IPInterfaceProperties ipProps = nic.GetIPProperties(); foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses) { // Only bother with external addresses if (ip.Address.AddressFamily != AddressFamily.InterNetwork) continue; if (ip.Address == targetIP) { IPv4InterfaceProperties ip4Props = ipProps.GetIPv4Properties(); return ip4Props.Index; } } } throw new Exception($"Error: Can't find network interface with the ip {targetIP}."); } public static int GetIPv4Index (this NetworkInterface nic) { IPInterfaceProperties ipProps = nic.GetIPProperties(); IPv4InterfaceProperties ip4Props = ipProps.GetIPv4Properties(); return ip4Props.Index; } } }