private void Page_Loaded(object sender, RoutedEventArgs e) { List <string> list = new List <string>(); IP_INTERFACE_INFO ips = Iphlpapi.GetInterfaceInfo(); list.Add(string.Format("Adapter count = {0}", ips.NumAdapters)); foreach (IP_ADAPTER_INDEX_MAP ip in ips.Adapter) { list.Add(string.Format("Index = {0}, Name = {1}", ip.Index, ip.Name)); } listView1.ItemsSource = list; }
private void button1_Click(object sender, EventArgs e) { if (!ValidateConfigs()) { return; } IPAddress ipAddress = new IPAddress(0); for (int j = 0; j < unloadRoutes.Count; j++) { if (listView1.Items[j].Checked && ValidateRoute(ref unloadRoutes[j].Destination, ref unloadRoutes[j].Prefix, ref unloadRoutes[j].Gateway, unloadRoutes[j].IPVersion)) { Config.SavedRouteItem savedRoute = unloadRoutes[j]; int ifIndex = 0; if (Global.NetworkInterfaces.ContainsKey(savedRoute.InterfaceGuid)) { ifIndex = Global.NetworkInterfaces[savedRoute.InterfaceGuid].Index; } else if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1 && NetworkInterface.Loopback.Guid == savedRoute.InterfaceGuid) { ifIndex = 1; } // load defaults if (defaultInterfaceMode.SelectedIndex == 0 && listView1.Items[j].SubItems[6].Text != "Active" || defaultInterfaceMode.SelectedIndex == 1) { if (unloadRoutes[j].IPVersion == 4) { ifIndex = int.Parse(Regex.Replace(defaultIPv4Interface.Text, @"^(\d+) .*$", "$1")); if (defaultIPv4GatewayMode.SelectedIndex != 3) { unloadRoutes[j].Gateway = defaultIPv4Gateway.Text; } } else { ifIndex = int.Parse(Regex.Replace(defaultIPv6Interface.Text, @"^(\d+) .*$", "$1")); if (defaultIPv6GatewayMode.SelectedIndex != 3) { unloadRoutes[j].Gateway = defaultIPv6Gateway.Text; } } } // unload route Iphlpapi.DeleteRoute(unloadRoutes[j].Destination, unloadRoutes[j].Prefix, unloadRoutes[j].Gateway, ifIndex.ToString()); } } Close(); }
internal static WinError.SeverityCode GetExtendedUdpTable(out IntPtr udpTable) { udpTable = IntPtr.Zero; WinError.SeverityCode status = Iphlpapi.GetExtendedUdpTable(IntPtr.Zero, out int pdwSize, true, Winsock.AddressFamily.AF_INET, Iprtrmib.UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID); while (status == WinError.SeverityCode.ERROR_INSUFFICIENT_BUFFER) { if (udpTable != IntPtr.Zero) Marshal.FreeHGlobal(udpTable); udpTable = Marshal.AllocHGlobal(pdwSize); status = Iphlpapi.GetExtendedUdpTable(udpTable, out pdwSize, true, Winsock.AddressFamily.AF_INET, Iprtrmib.UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID); } return status; }
public static PhysicalAddress SendARP(IPAddress destIP, IPAddress srcIP = null) { in_addr srcAddr = new in_addr((srcIP ?? IPAddress.Parse("0.0.0.0")).ToString()); in_addr destAddr = new in_addr(destIP.ToString()); UInt64 macAddr = 0; uint phyAddrLen = 8; ERROR result = Iphlpapi.SendARP(destAddr, srcAddr, ref macAddr, ref phyAddrLen); PhysicalAddress mac = new PhysicalAddress(new byte[] { }); if (result == ERROR.ERROR_SUCCESS) { mac = new PhysicalAddress(BitConverter.GetBytes(macAddr)); } return(mac); }
private void button8_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show(this, "Do you want to delete the following route ?\n" + "\nDestination: " + listView1.SelectedItems[0].SubItems[0].Text + "\nPrefix: " + listView1.SelectedItems[0].SubItems[1].Text + "\nGateway: " + listView1.SelectedItems[0].SubItems[2].Text + "\nInterface Index: " + listView1.SelectedItems[0].SubItems[3].Text, "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == System.Windows.Forms.DialogResult.No) { return; } Iphlpapi.DeleteRoute(listView1.SelectedItems[0].SubItems[0].Text, listView1.SelectedItems[0].SubItems[1].Text, listView1.SelectedItems[0].SubItems[2].Text, Regex.Replace(listView1.SelectedItems[0].SubItems[3].Text, @"^(\d+) .*$", "$1")); }
private void button1_Click(object sender, EventArgs e) { if (!ValidateRoute()) { return; } Iphlpapi.DeleteRoute(destination, prefix, gateway, interfaceIndex); Iphlpapi.MIB_IPFORWARD_TYPE type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_INDIRECT; int ifIndex = int.Parse(Regex.Replace(routeInterface.Text, @"^(\d+) .*$", "$1")); // if on-link set type to direct for XP if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { NetworkInterface nic; if (ifIndex == 1) { nic = NetworkInterface.Loopback; } else { nic = Global.NetworkInterfaces.Values.Where((i) => i.Index == ifIndex).First(); } if (ipVersion == 4) { if (nic.IPv4Address.Where((i) => i.Address == routeGateway.Text).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } //if (nic.Index == 1 && IP.CheckIfSameNetwork("127.0.0.1", routeGateway.Text, "255.0.0.0")) // type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } else { if (nic.IPv6Address.All.Where((i) => i.Address == routeGateway.Text).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } //if (nic.Index == 1 && IP.CheckIfSameNetwork("::1", routeGateway.Text, "128")) // type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } if (routeGateway.Text == "0.0.0.0" || routeGateway.Text == "::") { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } Iphlpapi.AddRoute(routeDestination.Text, routePrefix.Text, routeGateway.Text, ifIndex.ToString(), routeMetric.Text, type); Close(); }
internal static WinError.SeverityCode GetExtendedTcpTable(out IntPtr tcpTable) { tcpTable = IntPtr.Zero; //The initial status will return as ERROR_INSUFFICIENT_BUFFER, and pdwSize will contain the correct buffer size. WinError.SeverityCode status = Iphlpapi.GetExtendedTcpTable(IntPtr.Zero, out int pdwSize, true, Winsock.AddressFamily.AF_INET, Iprtrmib.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL); //The buffer may be slightly higher after the previous statement, so check. while (status == WinError.SeverityCode.ERROR_INSUFFICIENT_BUFFER) { if (tcpTable != IntPtr.Zero) Marshal.FreeHGlobal(tcpTable); tcpTable = Marshal.AllocHGlobal(pdwSize); status = Iphlpapi.GetExtendedTcpTable(tcpTable, out pdwSize, true, Winsock.AddressFamily.AF_INET, Iprtrmib.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL); } return status; }
/// <summary> /// /// </summary> /// <param name="tcpTableRow">The TCP Row which contains the connection to close.</param> /// <returns>An NTSTATUS code.</returns> public static WinError.SeverityCode CloseConnection(Tcpmib.MIB_TCPROW_OWNER_PID tcpTableRow) { //Sets the state value to delete. tcpTableRow.dwState = Tcpmib.TCPState.MIB_TCP_STATE_DELETE_TCB; //Allocate a region for the row details to reside. IntPtr tcpRowPtr = Marshal.AllocHGlobal(Marshal.SizeOf(tcpTableRow)); //Marshal the array into memory. Marshal.StructureToPtr(tcpTableRow, tcpRowPtr, false); //Overwrite the connection data. WinError.SeverityCode ntStatus = Iphlpapi.SetTcpEntry(tcpRowPtr); //Free the memory region. Marshal.FreeHGlobal(tcpRowPtr); return ntStatus; }
private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedItems.Count == 0) // || Regex.Replace(listView1.SelectedItems[0].SubItems[3].Text, @"^(\d+) .*$", "$1") == "1") { button7.Enabled = false; button8.Enabled = false; button9.Enabled = false; } else { if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { List <Iphlpapi.Route> routes = Iphlpapi.GetRoutes(Iphlpapi.FAMILY.AF_INET); Iphlpapi.Route route = routes.Find((i) => i.Destination == listView1.SelectedItems[0].SubItems[0].Text && i.Prefix == listView1.SelectedItems[0].SubItems[1].Text && i.Gateway == listView1.SelectedItems[0].SubItems[2].Text && i.InterfaceIndex.ToString() == Regex.Replace(listView1.SelectedItems[0].SubItems[3].Text, @"^(\d+) .*$", "$1") ); if (route != null) { if (route.Protocol == Iphlpapi.NL_ROUTE_PROTOCOL.MIB_IPPROTO_LOCAL) { button7.Enabled = false; button8.Enabled = false; button9.Enabled = false; return; } } } button7.Enabled = true; button8.Enabled = true; button9.Enabled = true; } }
private bool ValidateRoute() { IPAddress ipAddress = new IPAddress(0); string destination = routeDestination.Text; string prefix = routePrefix.Text; string gateway = routeGateway.Text; if (ipVersion == 4) { if (prefix == "") { prefix = "255.255.255.255"; } if (gateway == "") { gateway = "0.0.0.0"; } if (destination == "" || !IPAddress.TryParse(destination, out ipAddress) || ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork || Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0 && IP.CheckIfSameNetwork(destination, "240.0.0.0", "240.0.0.0")) { new BalloonTip("Warning", "Invalid IPv4 address", routeDestination, BalloonTip.ICON.WARNING); return(false); } if (!IP.ValidateIPv4Mask(ref prefix)) { new BalloonTip("Warning", "Invalid IPv4 subnet mask", routePrefix, BalloonTip.ICON.WARNING); return(false); } routeDestination.Text = IP.GetNetwork(destination, prefix); routePrefix.Text = prefix; if (!IPAddress.TryParse(gateway, out ipAddress) || ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork || Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1 && IP.CheckIfSameNetwork(gateway, "0.0.0.0", "255.0.0.0") && !IP.CheckIfSameNetwork(gateway, "0.0.0.0", "255.255.255.255") || Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0 && IP.CheckIfSameNetwork(gateway, "0.0.0.0", "255.255.255.255") || IP.CheckIfSameNetwork(gateway, "224.0.0.0", "224.0.0.0") || IP.CheckIfSameNetwork(gateway, "240.0.0.0", "240.0.0.0")) { new BalloonTip("Warning", "Invalid IPv4 gateway address", routeGateway, BalloonTip.ICON.WARNING); return(false); } routeGateway.Text = gateway; } else { if (prefix == "") { prefix = "128"; } if (gateway == "") { gateway = "::"; } if (destination == "" || !IPAddress.TryParse(destination, out ipAddress) || ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) { new BalloonTip("Warning", "Invalid IPv6 address", routeDestination, BalloonTip.ICON.WARNING); return(false); } if (!IP.ValidateIPv6Prefix(ref prefix)) { new BalloonTip("Warning", "Invalid IPv6 subnet prefix length. Value must between 0 and 128 (inclusive)", routePrefix, BalloonTip.ICON.WARNING); return(false); } routeDestination.Text = IP.GetNetwork(destination, prefix); routePrefix.Text = prefix; if (!IP.ValidateIPv6(ref gateway)) // && !Regex.IsMatch(gateway, @"^(::1|::)$") && IPAddress.TryParse(gateway, out ipAddress) && ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6) { new BalloonTip("Warning", "Invalid IPv6 address", routeGateway, BalloonTip.ICON.WARNING); return(false); } routeGateway.Text = gateway; } if (routeInterface.SelectedIndex == -1) { new BalloonTip("Information", "Select the interface through which to route", routeInterface, BalloonTip.ICON.INFO); return(false); } if (routeMetric.Text == "") { if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1) { routeMetric.Text = "0"; } else { routeMetric.Text = "1"; } } if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { if (ushort.Parse(routeMetric.Text) == 0) { new BalloonTip("Warning", "Route metric must be a value between 1 and 9999 (inclusive)", routeMetric, BalloonTip.ICON.WARNING); return(false); } } List <Iphlpapi.Route> routes = Iphlpapi.GetRoutes(Iphlpapi.FAMILY.AF_UNSPEC); if (routes.Where((i) => IPAddress.Parse(i.Destination).Equals(IPAddress.Parse(routeDestination.Text)) && (ipVersion == 4 ? IPAddress.Parse(i.Prefix).Equals(IPAddress.Parse(routePrefix.Text)) : int.Parse(i.Prefix) == int.Parse(routePrefix.Text)) && IPAddress.Parse(i.Gateway).Equals(IPAddress.Parse(routeGateway.Text)) && i.InterfaceIndex.ToString() == Regex.Replace(routeInterface.Text, @"^(\d+) .*$", "$1")).Count() > 0) { new BalloonTip("Error", "Route already exists", button1, BalloonTip.ICON.ERROR); return(false); } return(true); }
public static bool PutUp() { if (!Check()) { return(false); } if (handle != IntPtr.Zero) { return(true); } LoadingForm splash = LoadingForm.Create("Connecting to \"" + FriendlyName + "\" ..."); string duplicateName; if ((duplicateName = NetworkInterface.CheckIfIPv4Used(Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address, Guid)) != null) { splash.Stop(); Global.WriteLog("TAP Interface: IP address " + Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address + " already used by \"" + duplicateName + "\""); MessageBox.Show("\"" + FriendlyName + "\" can't use the IP address " + Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address + " because it's already used by \"" + duplicateName + "\".\n\n Set a different IPv4 address in Control Panel>Tools>Load balancing>Advanced.", "TAP Interface", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } handle = Kernel32.CreateFile(@"\\.\Global\{" + Guid + "}.tap", Kernel32.FILE_READ_DATA | Kernel32.FILE_WRITE_DATA, Kernel32.FILE_SHARE_READ | Kernel32.FILE_SHARE_WRITE, IntPtr.Zero, Kernel32.OPEN_EXISTING, Kernel32.FILE_ATTRIBUTE_SYSTEM | Kernel32.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (handle == Kernel32.INVALID_HANDLE_VALUE) { uint errorCode = Kernel32.GetLastError(); splash.Stop(); Global.WriteLog("TAP Interface: failed to connect to " + FriendlyName + ": " + Kernel32.GetLastErrorMessage(errorCode)); MessageBox.Show("Failed to connect to " + FriendlyName + ":\n" + Kernel32.GetLastErrorMessage(errorCode), "TAP Interface", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } // set TAP status to connected uint bytesReturned = 0; IntPtr pStatus = Marshal.AllocHGlobal(4); Marshal.Copy(BitConverter.GetBytes(1), 0, pStatus, 4); bool deviceStatus = Kernel32.DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS, pStatus, 4, pStatus, 4, ref bytesReturned, IntPtr.Zero); Marshal.FreeHGlobal(pStatus); // get TAP MAC address bytesReturned = 0; IntPtr pMac = Marshal.AllocHGlobal(8); bool macRetrieved = Kernel32.DeviceIoControl(handle, TAP_IOCTL_GET_MAC, pMac, 12, pMac, 12, ref bytesReturned, IntPtr.Zero); byte[] mac = new byte[bytesReturned]; Marshal.Copy(pMac, mac, 0, (int)bytesReturned); Mac = BitConverter.ToString(mac).Replace('-', ':'); Marshal.FreeHGlobal(pMac); // configure TAP splash.UpdateStatus("Configuring " + FriendlyName + " ..."); List <Iphlpapi.Adapter> adapters = Iphlpapi.GetAdapters(Iphlpapi.FAMILY.AF_UNSPEC); Iphlpapi.Adapter tap = adapters.Find(i => i.Guid == Guid); if (tap == null) { splash.Stop(); Global.WriteLog("TAP Interface: couldn't find " + FriendlyName + " index"); MessageBox.Show("Couldn't find " + FriendlyName + " index.", "TAP Interface", MessageBoxButtons.OK, MessageBoxIcon.Error); PutDown(); return(false); } Index = tap.InterfaceIndex; if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { NetworkInterface.SetInterfaceMetric(Mac, "1"); } else { NetworkInterface.SetInterfaceMetric(Index, "1"); } NetworkInterface.SetNetBios(Guid, false); NetworkInterface.ClearIPv4Addresses(Mac, Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address, Global.Config.LoadBalancer.IPv4LocalAddresses[0].Subnet); NetworkInterface.ClearGateways(Index); NetworkInterface.ClearIPv4DnsServers(Mac); if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { NetworkInterface.AddIPv4Gateway(Mac, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].Address, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].GatewayMetric.ToString()); } else { NetworkInterface.AddIPv4Gateway(Index, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].Address, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].GatewayMetric.ToString()); } NetworkInterface.SetIPv4DnsServer(FriendlyName, Global.Config.LoadBalancer.IPv4DnsAddresses[0]); splash.Stop(); if (handle != IntPtr.Zero && handle != Kernel32.INVALID_HANDLE_VALUE && deviceStatus && macRetrieved) { return(true); } else { return(false); } }
async void UpdateIPSessions() { try { while (!cts.IsCancellationRequested) { Kernel32.GetDeviceNameMap(); listView1.BeginUpdate(); sessions = Iphlpapi.GetIPSessions(); IPAddress ipAddress; // add/update items foreach (Iphlpapi.IPSession session in sessions) { // get process info string filePath = ""; int imageIndex = 0; if (processList.ContainsKey(session.OwningPid)) { imageIndex = processList[session.OwningPid].ImageListIndex; filePath = processList[session.OwningPid].Path; } else if (processList.Where(i => i.Value.Path == filePath).Count() > 0) { OwningProcess owningProcess = processList.Where(i => i.Value.Path == filePath).First().Value; processList.TryAdd(session.OwningPid, owningProcess); imageIndex = owningProcess.ImageListIndex; filePath = owningProcess.Path; } else { System.Drawing.Icon icon = null; filePath = Psapi.GetProcessFileName(session.OwningPid); if (filePath != "") { icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath); } if (icon != null) { imageList1.Images.Add(icon); imageIndex = imageList1.Images.Count - 1; OwningProcess owningProcess = new OwningProcess(); owningProcess.Path = filePath; owningProcess.ImageListIndex = imageIndex; processList.TryAdd(session.OwningPid, owningProcess); } } // add process in TV if (!treeView1.Nodes[0].Nodes.ContainsKey(Path.GetFileName(filePath) + " (" + session.OwningPid + ")")) { treeView1.Nodes[0].Nodes.Add(Path.GetFileName(filePath) + " (" + session.OwningPid + ")", Path.GetFileName(filePath) + " (" + session.OwningPid + ")", imageIndex, imageIndex).Parent.Expand(); } // filter if (session.SocketID.LocalEP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && comboBox1.SelectedIndex == 1 || session.SocketID.LocalEP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 && comboBox1.SelectedIndex == 0) { continue; } if (treeView1.SelectedNode != null && treeView1.SelectedNode.Parent != null) { if (session.OwningPid != uint.Parse(Regex.Replace(treeView1.SelectedNode.Text, @"^.*\((\d+)\)$", "$1"))) { continue; } } if (filterProtocol.SelectedIndex == 0 && session.SocketID.Protocol != IP.ProtocolFamily.TCP || filterProtocol.SelectedIndex == 1 && session.SocketID.Protocol != IP.ProtocolFamily.UDP) { continue; } // update existing items bool found = false; foreach (ListViewItem item in listView1.Items) { // find item if (session.SocketID.Equals(item.Tag)) { found = true; item.SubItems[6].Text = session.State; IPEndPoint remoteEP; // resolve IP if (resolveIP.Checked) { if (((IP.SocketID)item.Tag).Protocol == IP.ProtocolFamily.UDP) { if ((remoteEP = UdpDetector.Table.GetRemoteEP(((IP.SocketID)item.Tag).LocalEP)) != null) { if (!DnsRescords.ContainsKey(remoteEP.Address)) { ResolveIP(remoteEP.Address); } else if (DnsRescords[remoteEP.Address] != "") { item.SubItems[3].Text = DnsRescords[remoteEP.Address]; } } } else if (((IP.SocketID)item.Tag).Protocol == IP.ProtocolFamily.TCP) { if (!DnsRescords.ContainsKey(((IP.SocketID)item.Tag).RemoteEP.Address)) { ResolveIP(((IP.SocketID)item.Tag).RemoteEP.Address); } else if (DnsRescords[((IP.SocketID)item.Tag).RemoteEP.Address] != "") { item.SubItems[3].Text = DnsRescords[((IP.SocketID)item.Tag).RemoteEP.Address]; } } } else { if (!IPAddress.TryParse(item.SubItems[3].Text, out ipAddress)) { item.SubItems[3].Text = ((IP.SocketID)item.Tag).RemoteEP.Address.ToString(); } } // update remote UDP EP if (((IP.SocketID)item.Tag).Protocol == IP.ProtocolFamily.UDP && (item.SubItems[3].Text == "0.0.0.0" || item.SubItems[3].Text == "::" || item.SubItems[4].Text == "0") && (remoteEP = UdpDetector.Table.GetRemoteEP(((IP.SocketID)item.Tag).LocalEP)) != null) { item.SubItems[3].Text = remoteEP.Address.ToString(); item.SubItems[4].Text = remoteEP.Port.ToString(); } // update bytes if (getBytes.Checked == true) { ByteCounter.ByteTable.Bytes bytes = ByteCounter.Table.GetBytes((IP.SocketID)item.Tag); if (bytes.Received > 0 || bytes.Sent > 0) { item.SubItems[7].Text = Unit.AutoScale(bytes.Received, "B"); item.SubItems[8].Text = Unit.AutoScale(bytes.Sent, "B"); } else { item.SubItems[7].Text = ""; item.SubItems[8].Text = ""; } } } } if (!found) { listView1.Items.Add(new ListViewItem(new string[] { Path.GetFileName(filePath) + " (" + session.OwningPid + ")", session.SocketID.LocalEP.Address.ToString(), session.SocketID.LocalEP.Port.ToString(), session.SocketID.RemoteEP.Address.ToString(), session.SocketID.RemoteEP.Port.ToString(), session.SocketID.Protocol.ToString(), session.State, "", "" }, imageIndex)).Tag = session.SocketID; } } // delete items foreach (ListViewItem item in listView1.Items) { if (!sessions.Any((i) => i.SocketID.Equals(item.Tag)) || item.SubItems[1].Text.Contains(':') && comboBox1.SelectedIndex == 0 || !item.SubItems[1].Text.Contains(':') && comboBox1.SelectedIndex == 1 || filterProtocol.SelectedIndex == 0 && item.SubItems[5].Text != "TCP" || filterProtocol.SelectedIndex == 1 && item.SubItems[5].Text != "UDP") { item.Remove(); } else if (treeView1.SelectedNode != null && treeView1.SelectedNode.Parent != null) { if (item.SubItems[0].Text != treeView1.SelectedNode.Text) { item.Remove(); } } } foreach (KeyValuePair <uint, OwningProcess> process in processList) { if (sessions.Find(i => i.OwningPid == process.Key) == null) { treeView1.Nodes[0].Nodes.RemoveByKey(Path.GetFileName(process.Value.Path) + " (" + process.Key + ")"); OwningProcess value; processList.TryRemove(process.Key, out value); } } foreach (ColumnHeader column in listView1.Columns) { column.Width = -2; } listView1.Sort(); listView1.EndUpdate(); //Unit.Compare("10.5 KB", "10.5 B"); await TaskEx.Delay(1000); } } catch (Exception e) { Global.WriteLog(e.ToString()); } }
async void UpdateRoutes(CancellationTokenSource cts) { try { while (!cts.IsCancellationRequested) { listView1.BeginUpdate(); List <Iphlpapi.Route> routes = Iphlpapi.GetRoutes(Iphlpapi.FAMILY.AF_UNSPEC); List <Config.SavedRouteItem> savedRoutes = Global.Config.SavedRoutes.GetRoutes(Global.Config.SavedRoutes.Nodes[0]); Config.SavedRouteNode selectedNode = Global.Config.SavedRoutes.GetSelectedNode(treeView1); List <Config.SavedRouteItem> selectedRoutes = Global.Config.SavedRoutes.GetRoutes(selectedNode); // add/update items foreach (Iphlpapi.Route route in routes) { if (route.IPVersion == 4 && comboBox1.SelectedIndex == 1 || route.IPVersion == 6 && comboBox1.SelectedIndex == 0) { continue; } // skip disconnected interfaces if (Global.NetworkInterfaces.Values.Where((i) => i.Index == route.InterfaceIndex).Count() == 0 && route.InterfaceIndex != 1) { continue; } // calculate route metric if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1) { if (route.InterfaceIndex != 1) { route.Metric += Global.NetworkInterfaces.Values.Where((i) => i.Index == route.InterfaceIndex).FirstOrDefault().InterfaceMetric; } else { route.Metric += NetworkInterface.Loopback.InterfaceMetric; } } bool found = false; string ifIndex; if (route.InterfaceIndex == 1) { ifIndex = route.InterfaceIndex.ToString() + " (" + NetworkInterface.Loopback.Name + ")"; } else { ifIndex = route.InterfaceIndex.ToString() + " (" + Global.NetworkInterfaces.Values.Where((i) => i.Index == route.InterfaceIndex).FirstOrDefault().Name + ")"; } // filter routes bool filter = false; if (checkBox1.Checked) { if (selectedRoutes.Find(i => i.Destination == route.Destination && i.Prefix == route.Prefix && i.Gateway == route.Gateway && (Global.NetworkInterfaces.ContainsKey(i.InterfaceGuid) && Global.NetworkInterfaces[i.InterfaceGuid].Index == route.InterfaceIndex || NetworkInterface.Loopback.Guid == i.InterfaceGuid && NetworkInterface.Loopback.Index == route.InterfaceIndex)) == null) { filter = true; } } // TODO: update routes with all matching saved routes using Find() // update existing items foreach (ListViewItem item in listView1.Items) { if (item.SubItems[0].Text == route.Destination && item.SubItems[1].Text == route.Prefix && item.SubItems[2].Text == route.Gateway && item.SubItems[3].Text == ifIndex) { item.SubItems[4].Text = route.Age.ToString(); item.SubItems[5].Text = route.Metric.ToString(); Config.SavedRouteItem savedRoute = savedRoutes.Find(i => i.Destination == route.Destination && i.Prefix == route.Prefix && i.Gateway == route.Gateway && (Global.NetworkInterfaces.ContainsKey(i.InterfaceGuid) && Global.NetworkInterfaces[i.InterfaceGuid].Index == route.InterfaceIndex || NetworkInterface.Loopback.Guid == i.InterfaceGuid && NetworkInterface.Loopback.Index == route.InterfaceIndex)); if (savedRoute != null) { item.SubItems[6].Text = savedRoute.Name; } else { item.SubItems[6].Text = ""; } found = true; break; } } if (found || filter) { continue; } listView1.Items.Add(new ListViewItem(new string[] { route.Destination, route.Prefix, route.Gateway, ifIndex, route.Age.ToString(), route.Metric.ToString(), "" })); } // delete items foreach (ListViewItem item in listView1.Items) { string ifIndex = Regex.Replace(item.SubItems[3].Text, @"^(\d+) .*$", "$1"); // filter routes bool filter = false; if (checkBox1.Checked) { if (selectedRoutes.Find(i => i.Destination == item.SubItems[0].Text && i.Prefix == item.SubItems[1].Text && i.Gateway == item.SubItems[2].Text && (Global.NetworkInterfaces.ContainsKey(i.InterfaceGuid) && Global.NetworkInterfaces[i.InterfaceGuid].Index.ToString() == ifIndex || NetworkInterface.Loopback.Guid == i.InterfaceGuid && NetworkInterface.Loopback.Index.ToString() == ifIndex)) == null) { filter = true; } } if (routes.Find((i) => i.Destination == item.SubItems[0].Text && i.Prefix == item.SubItems[1].Text && i.Gateway == item.SubItems[2].Text && i.InterfaceIndex.ToString() == ifIndex) == null || item.SubItems[0].Text.Contains(':') && comboBox1.SelectedIndex == 0 || !item.SubItems[0].Text.Contains(':') && comboBox1.SelectedIndex == 1 || filter) { item.Remove(); } } foreach (ColumnHeader column in listView1.Columns) { column.Width = -2; } listView1.EndUpdate(); await TaskEx.Delay(1000); } } catch { } }
public static List <Dictionary <string, string> > GetNetCardInfo() { List <Dictionary <string, string> > results = new List <Dictionary <string, string> >(); Dictionary <int, Dictionary <string, string> > adapters = new Dictionary <int, Dictionary <string, string> >(); try { foreach (NetworkInterface netElement in NetworkInterface.GetAllNetworkInterfaces()) { Dictionary <string, string> card = new Dictionary <string, string>() { { "Index", netElement.GetIPProperties().GetIPv4Properties().Index.ToString() }, { "Name", netElement.Name }, { "PysicalAddr", "" }, { "DNSs", String.Join(", ", netElement.GetIPProperties().DnsAddresses) }, { "Gateways", "" }, { "IPs", "" }, { "Netmasks", "" }, { "arp", "" } }; card["PysicalAddrIni"] = netElement.GetPhysicalAddress().ToString(); for (int i = 0; i < card["PysicalAddrIni"].Length; i += 2) { card["PysicalAddr"] += card["PysicalAddrIni"].Substring(i, 2) + ":"; } foreach (GatewayIPAddressInformation address in netElement.GetIPProperties().GatewayAddresses.Reverse()) //Reverse so first IPv4 { card["Gateways"] += address.Address + ", "; } foreach (UnicastIPAddressInformation ip in netElement.GetIPProperties().UnicastAddresses.Reverse()) { //Reverse so first IPv4 card["IPs"] += ip.Address.ToString() + ", "; card["Netmasks"] += ip.IPv4Mask.ToString() + ", "; } //Delete last separator if (card["PysicalAddr"].Length > 0) { card["PysicalAddr"] = card["PysicalAddr"].Remove(card["PysicalAddr"].Length - 1); } if (card["Gateways"].Length > 0) { card["Gateways"] = card["Gateways"].Remove(card["Gateways"].Length - 2); } if (card["IPs"].Length > 0) { card["IPs"] = card["IPs"].Remove(card["IPs"].Length - 2); } if (card["Netmasks"].Length > 0) { card["Netmasks"] = card["Netmasks"].Remove(card["Netmasks"].Length - 2); } adapters[netElement.GetIPProperties().GetIPv4Properties().Index] = card; } //return results; // GET ARP values int bytesNeeded = 0; int result = Iphlpapi.GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { Console.WriteLine(" [X] Exception: {0}", result); } IntPtr buffer = IntPtr.Zero; // allocate sufficient memory for the result structure buffer = Marshal.AllocCoTaskMem(bytesNeeded); result = Iphlpapi.GetIpNetTable(buffer, ref bytesNeeded, false); if (result != 0) { Console.WriteLine(" [X] Exception allocating buffer: {0}", result); } // now we have the buffer, we have to marshal it. We can read the first 4 bytes to get the length of the buffer int entries = Marshal.ReadInt32(buffer); // increment the memory pointer by the size of the int IntPtr currentBuffer = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(int))); // allocate a list of entries List <MIB_IPNETROW> arpEntries = new List <MIB_IPNETROW>(); // cycle through the entries for (int index = 0; index < entries; index++) { arpEntries.Add((MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW))); } // sort the list by interface index List <MIB_IPNETROW> sortedARPEntries = arpEntries.OrderBy(o => o.dwIndex).ToList(); int currentIndexAdaper = -1; foreach (MIB_IPNETROW arpEntry in sortedARPEntries) { int indexAdapter = arpEntry.dwIndex; if (!adapters.ContainsKey(indexAdapter)) { Console.WriteLine("Error: No interface found with Index " + arpEntry.dwIndex.ToString()); continue; } currentIndexAdaper = indexAdapter; IPAddress ipAddr = new IPAddress(BitConverter.GetBytes(arpEntry.dwAddr)); byte[] macBytes = new byte[] { arpEntry.mac0, arpEntry.mac1, arpEntry.mac2, arpEntry.mac3, arpEntry.mac4, arpEntry.mac5 }; string physAddr = BitConverter.ToString(macBytes); ArpEntryType entryType = (ArpEntryType)arpEntry.dwType; adapters[arpEntry.dwIndex]["arp"] += $" {ipAddr,-22}{physAddr,-22}{entryType}\n"; } Iphlpapi.FreeMibTable(buffer); } catch (Exception ex) { Beaprint.PrintException(ex.Message); } results = adapters.Values.ToList(); return(results); }
public LoadForm(TreeView treeView) { InitializeComponent(); this.treeView = treeView; // resize Size minimumSize = ClientSize; Rectangle screenRectangle = RectangleToScreen(ClientRectangle); int titleBarHeight = screenRectangle.Top - Top; int borderThickness = screenRectangle.Left - Left; Rectangle workingArea = Screen.GetWorkingArea(this); Size clientSize = new Size(); if (minimumSize.Width > workingArea.Width - 2 * borderThickness) { clientSize.Width = workingArea.Width - 2 * borderThickness; } else { clientSize.Width = minimumSize.Width; } if (minimumSize.Height > workingArea.Height - titleBarHeight - borderThickness) { clientSize.Height = workingArea.Height - titleBarHeight - borderThickness; } else { clientSize.Height = minimumSize.Height; } AutoScrollMinSize = new System.Drawing.Size(minimumSize.Width, minimumSize.Height); ClientSize = new Size(clientSize.Width, clientSize.Height); // load routes IPAddress ipAddress = new IPAddress(0); Config.SavedRouteNode loadNode = Global.Config.SavedRoutes.GetSelectedNode(treeView); loadRoutes = Global.Config.SavedRoutes.GetRoutes(loadNode); activeRoutes = Iphlpapi.GetRoutes(Iphlpapi.FAMILY.AF_UNSPEC); foreach (Config.SavedRouteItem item in loadRoutes) { string interfaceIndex = "Not connected"; int ifIndex = 0; string status = "Not loaded"; if (ValidateRoute(ref item.Destination, ref item.Prefix, ref item.Gateway, item.IPVersion)) { if (Global.NetworkInterfaces.ContainsKey(item.InterfaceGuid) && (item.IPVersion == 4 && Global.NetworkInterfaces[item.InterfaceGuid].IPv4Enabled || item.IPVersion == 6 && Global.NetworkInterfaces[item.InterfaceGuid].IPv6Enabled)) { interfaceIndex = Global.NetworkInterfaces[item.InterfaceGuid].Index.ToString() + " (" + Global.NetworkInterfaces[item.InterfaceGuid].Name + " - "; ifIndex = Global.NetworkInterfaces[item.InterfaceGuid].Index; if (item.IPVersion == 4) { loadIPv4++; if (Global.NetworkInterfaces[item.InterfaceGuid].IPv4Address.Count > 0) { interfaceIndex += Global.NetworkInterfaces[item.InterfaceGuid].IPv4Address[0].Address; } else { interfaceIndex += "0.0.0.0"; } } else { loadIPv6++; if (Global.NetworkInterfaces[item.InterfaceGuid].IPv6Address.All.Count > 0) { interfaceIndex += Global.NetworkInterfaces[item.InterfaceGuid].IPv6Address.All[0].Address; } else { interfaceIndex += "::"; } } interfaceIndex += ")"; } else if (NetworkInterface.Loopback.Guid == item.InterfaceGuid && Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1 && (item.IPVersion == 4 && NetworkInterface.Loopback.IPv4Enabled || item.IPVersion == 6 && NetworkInterface.Loopback.IPv6Enabled)) { interfaceIndex = "1 (" + NetworkInterface.Loopback.Name + " - "; ifIndex = 1; if (item.IPVersion == 4) { loadIPv4++; interfaceIndex += "127.0.0.1)"; } else { loadIPv6++; interfaceIndex += "::1)"; } } else { if (item.IPVersion == 4) { loadIPv4++; NotConnectedIPv4Interfaces++; } else { loadIPv6++; NotConnectedIPv6Interfaces++; } } if (activeRoutes.Find(i => i.IPVersion == item.IPVersion && IPAddress.Parse(i.Destination).Equals(IPAddress.Parse(item.Destination)) && (i.IPVersion == 4 ? IPAddress.Parse(i.Prefix).Equals(IPAddress.Parse(item.Prefix)) : int.Parse(i.Prefix) == int.Parse(item.Prefix)) && IPAddress.Parse(i.Gateway).Equals(IPAddress.Parse(item.Gateway)) && i.InterfaceIndex == ifIndex) != null) { status = "Active"; } else if (activeRoutes.Find(i => i.IPVersion == item.IPVersion && IPAddress.Parse(i.Destination).Equals(IPAddress.Parse(item.Destination)) && (i.IPVersion == 4 ? IPAddress.Parse(i.Prefix).Equals(IPAddress.Parse(item.Prefix)) : int.Parse(i.Prefix) == int.Parse(item.Prefix)) && IPAddress.Parse(i.Gateway).Equals(IPAddress.Parse(item.Gateway))) != null) { status = "Active on a different interface"; if (item.IPVersion == 4) { NotActiveIPv4Routes++; } else { NotActiveIPv6Routes++; } } else if (activeRoutes.Find(i => i.IPVersion == item.IPVersion && IPAddress.Parse(i.Destination).Equals(IPAddress.Parse(item.Destination)) && (i.IPVersion == 4 ? IPAddress.Parse(i.Prefix).Equals(IPAddress.Parse(item.Prefix)) : int.Parse(i.Prefix) == int.Parse(item.Prefix)) ) != null) { status = "Active with a different gateway"; if (item.IPVersion == 4) { NotActiveIPv4Routes++; } else { NotActiveIPv6Routes++; } } else { if (item.IPVersion == 4) { NotActiveIPv4Routes++; } else { NotActiveIPv6Routes++; } } } else { if (item.IPVersion == 4) { loadIPv4++; NotActiveIPv4Routes++; NotConnectedIPv4Interfaces++; } else { loadIPv6++; NotActiveIPv6Routes++; NotConnectedIPv6Interfaces++; } } ListViewItem lvItem = new ListViewItem(new string[] { item.Destination, item.Prefix, item.Gateway, interfaceIndex, item.Metric.ToString(), item.Name, status }); lvItem.Tag = item; listView1.Items.Add(lvItem).Checked = true; } foreach (ColumnHeader column in listView1.Columns) { column.Width = -2; } // load configs defaultInterfaceMode.SelectedIndex = 0; defaultIPv4GatewayMode.SelectedIndex = 3; defaultIPv6GatewayMode.SelectedIndex = 3; foreach (NetworkInterface nic in Global.NetworkInterfaces.Values) { if (nic.IPv4Enabled) { defaultIPv4Interface.Items.Add(nic.Index.ToString() + " (" + nic.Name + " - " + (nic.IPv4Address.Count > 0 ? nic.IPv4Address.FirstOrDefault().Address : "0.0.0.0")); } } if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1) { if (NetworkInterface.Loopback.IPv4Enabled) { defaultIPv4Interface.Items.Add("1 (" + NetworkInterface.Loopback.Name + " - 127.0.0.1)"); } } foreach (NetworkInterface nic in Global.NetworkInterfaces.Values) { if (nic.IPv6Enabled) { defaultIPv6Interface.Items.Add(nic.Index.ToString() + " (" + nic.Name + " - " + (nic.IPv6Address.All.Count > 0 ? nic.IPv6Address.All.FirstOrDefault().Address : "0.0.0.0")); } } if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1) { if (NetworkInterface.Loopback.IPv6Enabled) { defaultIPv6Interface.Items.Add("1 (" + NetworkInterface.Loopback.Name + " - ::1)"); } } }
private void button1_Click(object sender, EventArgs e) { if (!ValidateRoute()) { return; } Iphlpapi.MIB_IPFORWARD_TYPE type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_INDIRECT; int ifIndex = int.Parse(Regex.Replace(routeInterface.Text, @"^(\d+) .*$", "$1")); // if on-link set type to direct for XP if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { NetworkInterface nic; if (ifIndex == 1) { nic = NetworkInterface.Loopback; } else { nic = Global.NetworkInterfaces.Values.Where((i) => i.Index == ifIndex).First(); } if (ipVersion == 4) { if (nic.IPv4Address.Where((i) => i.Address == routeGateway.Text).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } //if (nic.Index == 1 && IP.CheckIfSameNetwork("127.0.0.1", routeGateway.Text, "255.0.0.0")) // type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } else { if (nic.IPv6Address.All.Where((i) => i.Address == routeGateway.Text).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } //if (nic.Index == 1 && IP.CheckIfSameNetwork("::1", routeGateway.Text, "128")) // type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } if (routeGateway.Text == "0.0.0.0" || routeGateway.Text == "::") { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } Iphlpapi.AddRoute(routeDestination.Text, routePrefix.Text, routeGateway.Text, ifIndex.ToString(), routeMetric.Text, type); // save route if (checkBox1.Checked) { Config.SavedRouteItem savedRoute = new Config.SavedRouteItem(); savedRoute.Name = savedRouteName.Text; savedRoute.Destination = routeDestination.Text; savedRoute.Prefix = routePrefix.Text; savedRoute.Gateway = routeGateway.Text; if (ifIndex == 1) { savedRoute.InterfaceGuid = NetworkInterface.Loopback.Guid; } else { savedRoute.InterfaceGuid = Global.NetworkInterfaces.Values.Where((i) => i.Index == ifIndex).FirstOrDefault().Guid; } savedRoute.Metric = ushort.Parse(routeMetric.Text); savedRoute.IPVersion = ipVersion; int result = Global.Config.SavedRoutes.AddNode(treeView1, savedRoute); if (result == 1) { new BalloonTip("Error", "Invalid destination", button1, BalloonTip.ICON.ERROR); return; } if (result == 2) { DialogResult dialogResult = MessageBox.Show("Route name already used at current destination.\nDo you want to overwrite?", "Overwrite confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (dialogResult == DialogResult.No) { return; } if (treeView1.SelectedNode.ImageIndex == (int)Config.SavedRouteNode.ImageIndex.Group) { treeView1.SelectedNode = treeView1.SelectedNode.Nodes.Find(savedRouteName.Text, false).First(); } else if (treeView1.SelectedNode.Name != savedRouteName.Text) { treeView1.SelectedNode = treeView1.SelectedNode.Parent.Nodes.Find(savedRouteName.Text, false).First(); } Global.Config.SavedRoutes.DeleteNode(treeView1); Global.Config.SavedRoutes.AddNode(treeView1, savedRoute); } } Close(); }
public override IEnumerable <CommandDTOBase?> Execute(string[] args) { // adapted from Fred's code at https://social.technet.microsoft.com/Forums/lync/en-US/e949b8d6-17ad-4afc-88cd-0019a3ac9df9/powershell-alternative-to-arp-a?forum=ITCG var adapterIdToInterfaceMap = new SortedDictionary <uint, ArpTableDTO>(); // build a mapping of index -> interface information foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces()) { BuildIndexToInterfaceMap(networkInterface, adapterIdToInterfaceMap); } var bytesNeeded = 0; var result = Iphlpapi.GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); if (result != Win32Error.InsufficientBuffer) { throw new Exception($"GetIpNetTable: Expected insufficient buffer but got {result}"); } var buffer = Marshal.AllocCoTaskMem(bytesNeeded); try { result = Iphlpapi.GetIpNetTable(buffer, ref bytesNeeded, false); if (result != 0) { throw new Exception($"GetIpNetTable error: {result}"); } // now we have the buffer, we have to marshal it. We can read the first 4 bytes to get the length of the buffer var entries = Marshal.ReadInt32(buffer); // increment the memory pointer by the size of the int var currentBuffer = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(int))); // allocate a list of entries var arpEntries = new List <Iphlpapi.MIB_IPNETROW>(); // cycle through the entries for (var index = 0; index < entries; index++) { arpEntries.Add((Iphlpapi.MIB_IPNETROW)Marshal.PtrToStructure( new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(Iphlpapi.MIB_IPNETROW)))), typeof(Iphlpapi.MIB_IPNETROW))); } // sort the list by interface index var sortedArpEntries = arpEntries.OrderBy(o => o.dwIndex).ToList(); uint?currentAdapterIndex = null; foreach (var arpEntry in sortedArpEntries) { var adapterIndex = (uint)arpEntry.dwIndex; if (currentAdapterIndex != adapterIndex) { if (!adapterIdToInterfaceMap.ContainsKey(adapterIndex)) { adapterIdToInterfaceMap[adapterIndex] = new ArpTableDTO(adapterIndex, "n/a", "n/a"); } currentAdapterIndex = adapterIndex; } var ipAddress = new IPAddress(BitConverter.GetBytes(arpEntry.dwAddr)); var macBytes = new[] { arpEntry.mac0, arpEntry.mac1, arpEntry.mac2, arpEntry.mac3, arpEntry.mac4, arpEntry.mac5 }; var physicalAddress = BitConverter.ToString(macBytes); var entryType = (Iphlpapi.ArpEntryType)arpEntry.dwType; var entry = new ArpEntry( ipAddress.ToString(), physicalAddress, entryType.ToString() ); adapterIdToInterfaceMap[adapterIndex].Entries.Add(entry); } } finally { if (buffer != IntPtr.Zero) { Iphlpapi.FreeMibTable(buffer); } } foreach (var adapter in adapterIdToInterfaceMap) { yield return(adapter.Value); } }
public static List <Tcp6ConnectionInfo> GetIP6(Action <string> log) { List <Tcp6ConnectionInfo> resultTable = new List <Tcp6ConnectionInfo>(); try { // Get size first int tableSize = 0; int errorCode = Iphlpapi.GetTcp6Table2(IntPtr.Zero, ref tableSize, false); if (errorCode != 122) // 122 return when we pass small buffer but output the expected buffer { throw new Exception("Can't read table size, error code: " + errorCode); } IntPtr memoryPointer = IntPtr.Zero; // Where we allocate try { // Get Table data: memoryPointer = Marshal.AllocHGlobal(tableSize); errorCode = Iphlpapi.GetTcp6Table2(memoryPointer, ref tableSize, false); if (errorCode != 0) { throw new Exception("Can't read table data, error code: " + errorCode); } var tableInfoStruct = (Iphlpapi.MIB_TCP6TABLE2)Marshal.PtrToStructure(memoryPointer, typeof(Iphlpapi.MIB_TCP6TABLE2)); // The other rows are sequentially after the size: IntPtr tableRowsPointer = (IntPtr)((long)memoryPointer + Marshal.SizeOf(tableInfoStruct.dwNumEntries)); for (int i = 0; i < tableInfoStruct.dwNumEntries; i++) { Iphlpapi.MIB_TCP6ROW2 tcpRow = (Iphlpapi.MIB_TCP6ROW2) Marshal.PtrToStructure(tableRowsPointer, typeof(Iphlpapi.MIB_TCP6ROW2)); resultTable.Add(new Tcp6ConnectionInfo(tcpRow)); // Advance in memory the size of the row: tableRowsPointer = (IntPtr)((long)tableRowsPointer + Marshal.SizeOf(tcpRow)); } } catch (OutOfMemoryException exMem) { log("Can't allocated data, error:\n" + exMem); } catch (Exception exReadData) { log("Error occured while getting data, error:\n" + exReadData); } finally { Marshal.FreeHGlobal(memoryPointer); memoryPointer = IntPtr.Zero; } } catch (Exception exMain) { log("Error occured, error:\n" + exMain); } return(resultTable); }
public static IEnumerable <UdpConnectionInfo> GetUdpConnections(IPVersion ipVersion, Dictionary <int, Process> processesByPid = null) { int bufferSize = 0; List <UdpConnectionInfo> udpTableRecords = new List <UdpConnectionInfo>(); int ulAf = AF_INET; if (ipVersion == IPVersion.IPv6) { ulAf = AF_INET6; } // Getting the initial size of UDP table. uint result = Iphlpapi.GetExtendedUdpTable(IntPtr.Zero, ref bufferSize, true, ulAf, UdpTableClass.UDP_TABLE_OWNER_PID); // Allocating memory as an IntPtr with the bufferSize. IntPtr udpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize); try { // The IntPtr from last call, udpTableRecoresPtr must be used in the subsequent // call and passed as the first parameter. result = Iphlpapi.GetExtendedUdpTable(udpTableRecordsPtr, ref bufferSize, true, ulAf, UdpTableClass.UDP_TABLE_OWNER_PID); // If not zero, call failed. if (result != 0) { return(new List <UdpConnectionInfo>()); } // Marshals data fron an unmanaged block of memory to the // newly allocated managed object 'udpRecordsTable' of type // 'MIB_UDPTABLE_OWNER_PID' to get number of entries of TCP // table structure. // Determine if IPv4 or IPv6. if (ipVersion == IPVersion.IPv4) { MIB_UDPTABLE_OWNER_PID udpRecordsTable = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(udpTableRecordsPtr, typeof(MIB_UDPTABLE_OWNER_PID)); IntPtr tableRowPtr = (IntPtr)((long)udpTableRecordsPtr + Marshal.SizeOf(udpRecordsTable.dwNumEntries)); // Read and parse the UDP records from the table and store them in list // 'UdpConnection' structure type objects. for (int i = 0; i < udpRecordsTable.dwNumEntries; i++) { MIB_UDPROW_OWNER_PID udpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDPROW_OWNER_PID)); udpTableRecords.Add(new UdpConnectionInfo( Protocol.UDP, new IPAddress(udpRow.localAddr), BitConverter.ToUInt16(new byte[2] { udpRow.localPort[1], udpRow.localPort[0] }, 0), udpRow.owningPid, GetProcessNameByPid(udpRow.owningPid, processesByPid))); tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(udpRow)); } } else if (ipVersion == IPVersion.IPv6) { MIB_UDP6TABLE_OWNER_PID udpRecordsTable = (MIB_UDP6TABLE_OWNER_PID) Marshal.PtrToStructure(udpTableRecordsPtr, typeof(MIB_UDP6TABLE_OWNER_PID)); IntPtr tableRowPtr = (IntPtr)((long)udpTableRecordsPtr + Marshal.SizeOf(udpRecordsTable.dwNumEntries)); // Read and parse the UDP records from the table and store them in list // 'UdpConnection' structure type objects. for (int i = 0; i < udpRecordsTable.dwNumEntries; i++) { MIB_UDP6ROW_OWNER_PID udpRow = (MIB_UDP6ROW_OWNER_PID) Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDP6ROW_OWNER_PID)); udpTableRecords.Add(new UdpConnectionInfo( Protocol.UDP, new IPAddress(udpRow.localAddr, udpRow.localScopeId), BitConverter.ToUInt16(new byte[2] { udpRow.localPort[1], udpRow.localPort[0] }, 0), udpRow.owningPid, GetProcessNameByPid(udpRow.owningPid, processesByPid))); tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(udpRow)); } } } catch (OutOfMemoryException outOfMemoryException) { throw outOfMemoryException; } catch (Exception exception) { throw exception; } finally { Marshal.FreeHGlobal(udpTableRecordsPtr); } return(udpTableRecords != null?udpTableRecords.Distinct().ToList() : new List <UdpConnectionInfo>()); }
private void button1_Click(object sender, EventArgs e) { if (!ValidateConfigs()) { return; } IPAddress ipAddress = new IPAddress(0); for (int j = 0; j < loadRoutes.Count; j++) { if (listView1.Items[j].Checked && ValidateRoute(ref loadRoutes[j].Destination, ref loadRoutes[j].Prefix, ref loadRoutes[j].Gateway, loadRoutes[j].IPVersion)) { Config.SavedRouteItem savedRoute = loadRoutes[j]; int ifIndex = 0; if (Global.NetworkInterfaces.ContainsKey(savedRoute.InterfaceGuid)) { ifIndex = Global.NetworkInterfaces[savedRoute.InterfaceGuid].Index; } else if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1 && NetworkInterface.Loopback.Guid == savedRoute.InterfaceGuid) { ifIndex = 1; } // load defaults if (defaultInterfaceMode.SelectedIndex == 0 && ifIndex == 0 || defaultInterfaceMode.SelectedIndex == 1) { if (loadRoutes[j].IPVersion == 4) { ifIndex = int.Parse(Regex.Replace(defaultIPv4Interface.Text, @"^(\d+) .*$", "$1")); if (defaultIPv4GatewayMode.SelectedIndex != 3) { loadRoutes[j].Gateway = defaultIPv4Gateway.Text; } } else { ifIndex = int.Parse(Regex.Replace(defaultIPv6Interface.Text, @"^(\d+) .*$", "$1")); if (defaultIPv6GatewayMode.SelectedIndex != 3) { loadRoutes[j].Gateway = defaultIPv6Gateway.Text; } } } // if on-link set type to direct for XP Iphlpapi.MIB_IPFORWARD_TYPE type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_INDIRECT; NetworkInterface nic; if (ifIndex == 1) { nic = NetworkInterface.Loopback; } else { nic = Global.NetworkInterfaces.Values.Where((i) => i.Index == ifIndex).First(); } if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { if (savedRoute.IPVersion == 4) { if (nic.IPv4Address.Where((i) => i.Address == savedRoute.Gateway).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } else { if (nic.IPv6Address.All.Where((i) => i.Address == savedRoute.Gateway).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } if (savedRoute.Gateway == "0.0.0.0" || savedRoute.Gateway == "::") { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } // correction for Vista->XP transitioned saved route if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { if (IPAddress.TryParse(savedRoute.Gateway, out ipAddress)) { if (IPAddress.Parse(savedRoute.Gateway).GetAddressBytes().Max() == 0) { if (savedRoute.IPVersion == 4) { savedRoute.Gateway = nic.IPv4Address.First().Address; } else { savedRoute.Gateway = nic.IPv6Address.All.First().Address; } } } if (savedRoute.Metric == 0) { savedRoute.Metric = 1; } } Iphlpapi.DeleteRoute(savedRoute.Destination, savedRoute.Prefix, savedRoute.Gateway, ifIndex.ToString()); Iphlpapi.AddRoute(savedRoute.Destination, savedRoute.Prefix, savedRoute.Gateway, ifIndex.ToString(), savedRoute.Metric.ToString(), type); if (updateSavedRoutesCheckBox.Checked == true) { // TODO: update saved route with new interface + gw } } else { MessageBox.Show("Could not load route:\nDestination: " + loadRoutes[j].Destination + "\nPrefix: " + loadRoutes[j].Prefix + "\nGateway: " + loadRoutes[j].Gateway + "\nIP version: " + loadRoutes[j].IPVersion, "Invalid route", MessageBoxButtons.OK, MessageBoxIcon.Error); } } Close(); }
/// <summary> /// Load in FIB /// </summary> /// <param name="nic">Override saved egress interface</param> /// <param name="gateway">Override saved gateway</param> /// <param name="metric">Override saved metric</param> public void Load(NetworkInterface nic = null, string gateway = null, int metric = -1) { if (nic == null) { if (Global.NetworkInterfaces.ContainsKey(this.InterfaceGuid)) { nic = Global.NetworkInterfaces[this.InterfaceGuid]; } else if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) > -1 && NetworkInterface.Loopback.Guid == this.InterfaceGuid) { nic = NetworkInterface.Loopback; } } if (gateway == null) { gateway = Gateway; } if (metric < 0) { metric = Metric; } // if on-link set type to direct for XP Iphlpapi.MIB_IPFORWARD_TYPE type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_INDIRECT; if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { if (this.IPVersion == 4) { if (nic.IPv4Address.Where((i) => i.Address == gateway).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } else { if (nic.IPv6Address.All.Where((i) => i.Address == gateway).Count() > 0) { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } if (gateway == "0.0.0.0" || gateway == "::") { type = Iphlpapi.MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT; } } // correction for Vista->XP transitioned saved route if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0) { if (IPAddress.TryParse(gateway, out IPAddress ipAddress)) { if (IPAddress.Parse(gateway).GetAddressBytes().Max() == 0) { if (this.IPVersion == 4) { gateway = nic.IPv4Address.First().Address; } else { gateway = nic.IPv6Address.All.First().Address; } } } if (metric == 0) { metric = 1; } } Iphlpapi.DeleteRoute(this.Destination, this.Prefix, gateway, nic.Index.ToString()); Iphlpapi.AddRoute(this.Destination, this.Prefix, gateway, nic.Index.ToString(), metric.ToString(), type); }