public static void DeleteRoute(Ip4RouteEntry routeEntry) { var route = new NativeMethods.MIB_IPFORWARDROW { dwForwardDest = BitConverter.ToUInt32(IPAddress.Parse(routeEntry.DestinationIP.ToString()).GetAddressBytes(), 0), dwForwardMask = BitConverter.ToUInt32(IPAddress.Parse(routeEntry.SubnetMask.ToString()).GetAddressBytes(), 0), dwForwardNextHop = BitConverter.ToUInt32(IPAddress.Parse(routeEntry.GatewayIP.ToString()).GetAddressBytes(), 0), dwForwardMetric1 = 99, dwForwardType = Convert.ToUInt32(3), //Default to 3 dwForwardProto = Convert.ToUInt32(3), //Default to 3 dwForwardAge = 0, dwForwardIfIndex = Convert.ToUInt32(routeEntry.InterfaceIndex) }; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeMethods.MIB_IPFORWARDROW))); try { Marshal.StructureToPtr(route, ptr, false); var status = NativeMethods.DeleteIpForwardEntry(ptr); } finally { Marshal.FreeHGlobal(ptr); } }
public static void CreateRoute(string destination, string mask, int interfaceIndex, int metric) { NetworkAdaptor adaptor = NicInterface.GetNetworkAdaptor(interfaceIndex); var route = new NativeMethods.MIB_IPFORWARDROW { dwForwardDest = BitConverter.ToUInt32(IPAddress.Parse(destination).GetAddressBytes(), 0), dwForwardMask = BitConverter.ToUInt32(IPAddress.Parse(mask).GetAddressBytes(), 0), dwForwardNextHop = BitConverter.ToUInt32(IPAddress.Parse(adaptor.PrimaryGateway.ToString()).GetAddressBytes(), 0), dwForwardMetric1 = Convert.ToUInt32(metric), dwForwardType = Convert.ToUInt32(3), //Default to 3 dwForwardProto = Convert.ToUInt32(3), //Default to 3 dwForwardAge = 0, dwForwardIfIndex = Convert.ToUInt32(interfaceIndex) }; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeMethods.MIB_IPFORWARDROW))); try { Marshal.StructureToPtr(route, ptr, false); var status = NativeMethods.CreateIpForwardEntry(ptr); } finally { Marshal.FreeHGlobal(ptr); } }