using System; using System.Linq; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; namespace Netch.Utils { public static class RouteHelper { /// /// 将 Luid 转换为 Index 索引 /// /// /// [DllImport("RouteHelper.bin", CallingConvention = CallingConvention.Cdecl)] public static extern uint ConvertLuidToIndex(ulong id); /// /// 绑定 IP 地址(Windows XP) /// /// /// /// /// [DllImport("RouteHelper.bin", CallingConvention = CallingConvention.Cdecl)] public static extern bool CreateIPv4(string address, string netmask, uint index); /// /// 绑定 IP 地址 /// /// /// /// /// /// [DllImport("RouteHelper.bin", CallingConvention = CallingConvention.Cdecl)] public static extern bool CreateUnicastIP(AddressFamily inet, string address, byte cidr, uint index); /// /// 创建路由 /// /// /// /// /// /// /// [DllImport("RouteHelper.bin", CallingConvention = CallingConvention.Cdecl)] public static extern bool CreateRoute(AddressFamily inet, string address, byte cidr, string gateway, uint index, uint metric = 1); /// /// 删除路由 /// /// /// /// /// /// /// [DllImport("RouteHelper.bin", CallingConvention = CallingConvention.Cdecl)] public static extern bool DeleteRoute(AddressFamily inet, string address, byte cidr, string gateway, uint index); /// /// 使用索引获取适配器 /// /// /// public static NetworkInterface GetInterfaceByIndex(ulong index) { NetworkInterface adapter = null; var list = NetworkInterface.GetAllNetworkInterfaces(); for (int i = 0; i < list.Length; i++) { if (list[i].Supports(NetworkInterfaceComponent.IPv4)) { if (list[i].GetIPProperties().GetIPv4Properties().Index == Convert.ToInt32(index)) { adapter = list[i]; break; } } else if (list[i].Supports(NetworkInterfaceComponent.IPv6)) { if (list[i].GetIPProperties().GetIPv6Properties().Index == Convert.ToInt32(index)) { adapter = list[i]; break; } } else { return null; } } return adapter; } /// /// 使用名称获取适配器索引 /// /// /// public static ulong GetInterfaceIndexByDescription(string name) { var ada = NetworkInterface.GetAllNetworkInterfaces() .First(nic => { if (nic.Description.Equals(name)) { return true; } return false; }); int index = 0; if (ada.Supports(NetworkInterfaceComponent.IPv4)) { index = ada.GetIPProperties().GetIPv4Properties().Index; } else if (ada.Supports(NetworkInterfaceComponent.IPv6)) { index = ada.GetIPProperties().GetIPv6Properties().Index; } return Convert.ToUInt64(index); } } }