/// <summary> /// Modifie une entrée ARP existante. /// </summary> /// <param name="entryToSet">Entrée à modifier.</param> /// <param name="IPInterface">Nouvelle interface.</param> /// <param name="PhysicalAddress">Nouvelle adresse physique (MAC).</param> /// <param name="Address">Nouvelle adresse IP.</param> /// <param name="Flags">Flag ARP.</param> /// <returns></returns> public int ChangeArpEntry(ref ArpEntry entryToSet, int IPInterface, byte[] PhysicalAddress, IPAddress Address, ArpFlags Flags) { int ret = -1; try { MIB_IPNETROW ipArp = entryToSet._ipArpNative; ipArp.dwIndex = IPInterface; ipArp.dwType = Flags; ipArp.dwAddr = (uint)BitConverter.ToInt32(Address.GetAddressBytes(), 0); ipArp.bPhysAddr = PhysicalAddress; ipArp.dwPhysAddrLen = PhysicalAddress.Length; //Appel api pour modifier l'entrée. ret = NativeMethods.SetIpNetEntry(ref ipArp); if (ret == 0) { entryToSet.Index = ipArp.dwIndex; entryToSet.Address = Address; entryToSet.Flags = Flags; entryToSet.MacAddress = PhysicalAddress; entryToSet.RelatedInterface = _adapters.GetAdapter(IPInterface); } } catch (Exception) { } return(ret); }
public void CreateSetDeleteIpNetEntryTest() { var target = new IN_ADDR(192, 168, 0, 202); Assert.That(GetBestRoute(target, 0, out var fwdRow), Is.Zero); var mibrow = new MIB_IPNETROW(target, fwdRow.dwForwardIfIndex, SendARP(target), MIB_IPNET_TYPE.MIB_IPNET_TYPE_DYNAMIC); MIB_IPNETTABLE t1 = null; Assert.That(() => t1 = GetIpNetTable(true), Throws.Nothing); if (t1 != null && HasVal(t1, mibrow)) { Assert.That(DeleteIpNetEntry(mibrow), Is.Zero); } Assert.That(CreateIpNetEntry(mibrow), Is.Zero); var t = GetIpNetTable(true); Assert.That(HasVal(t, mibrow), Is.True); Assert.That(SetIpNetEntry(mibrow), Is.Zero); Assert.That(DeleteIpNetEntry(mibrow), Is.Zero); var t3 = GetIpNetTable(true); Assert.That(HasVal(t3, mibrow), Is.False); bool HasVal(IEnumerable <MIB_IPNETROW> tb, MIB_IPNETROW r) => tb.Any(tr => tr.dwAddr.S_addr == r.dwAddr.S_addr && tr.dwIndex == r.dwIndex && tr.bPhysAddr.SequenceEqual(r.bPhysAddr)); }
/// <summary> /// Get the IP and MAC addresses of all known devices on the LAN /// </summary> /// <remarks> /// 1) This table is not updated often - it can take some human-scale time /// to notice that a device has dropped off the network, or a new device /// has connected. /// 2) This discards non-local devices if they are found - these are multicast /// and can be discarded by IP address range. /// </remarks> /// <returns></returns> public static Dictionary <IPAddress, PhysicalAddress> GetIPNetTableDictionary() { Dictionary <IPAddress, PhysicalAddress> all = new Dictionary <IPAddress, PhysicalAddress>(); int spaceForNetTable = 0; // Get the space needed // We do that by requesting the table, but not giving any space at all. // The return value will tell us how much we actually need. GetIpNetTable(IntPtr.Zero, ref spaceForNetTable, false); // Allocate the space // We use a try-finally block to ensure release. IntPtr rawTable = IntPtr.Zero; try { rawTable = Marshal.AllocCoTaskMem(spaceForNetTable); // Get the actual data int errorCode = GetIpNetTable(rawTable, ref spaceForNetTable, false); if (errorCode != 0) { // Failed for some reason - can do no more here. throw new Exception(string.Format("Unable to retrieve network table. Error code {0}", errorCode)); } // Get the rows count int rowsCount = Marshal.ReadInt32(rawTable); IntPtr currentBuffer = new IntPtr(rawTable.ToInt64() + Marshal.SizeOf(typeof(Int32))); // Convert the raw table to individual entries MIB_IPNETROW[] rows = new MIB_IPNETROW[rowsCount]; for (int index = 0; index < rowsCount; index++) { rows[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } // Define the dummy entries list (we can discard these) PhysicalAddress virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }); PhysicalAddress broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }); foreach (MIB_IPNETROW row in rows) { IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); byte[] rawMAC = new byte[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 }; PhysicalAddress pa = new PhysicalAddress(rawMAC); if (!pa.Equals(virtualMAC) && !pa.Equals(broadcastMAC)) { if (!all.ContainsKey(ip)) { all.Add(ip, pa); } } } } finally { // Release the memory. Marshal.FreeCoTaskMem(rawTable); } return(all); }
/// <summary> /// Retrieves the IPv4 to physical address mapping table. /// </summary> /// <param name="sort">Specifies whether the returned mapping table should be sorted in ascending order by IP address.</param> /// <returns>The IPv4 to physical address mapping table.</returns> public static MIB_IPNETROW[] GetIpNetTable(bool sort) { IntPtr pBuffer = IntPtr.Zero; try { // Used to hold the size of the returned data. int size = 0; // Call GetIpNetTable the first time to determine the size of the data to be returned. int result = GetIpNetTable(IntPtr.Zero, ref size, sort); // We should receive an 'Insufficient Buffer' error, otherwise throw an exception. if (result != ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } // Allocate the memory buffer of required size. pBuffer = Marshal.AllocCoTaskMem(size); // Call GetIpNetTable the second time to retreive the actual data. result = GetIpNetTable(pBuffer, ref size, sort); // If the result is not 0 (no error), then throw an exception. if (result != 0) { throw new Win32Exception(result); } // Read the first four bytes from the buffer to determine the number of MIB_IPNETROW structures returned. int count = Marshal.ReadInt32(pBuffer); //Declare an array to contain the returned data. MIB_IPNETROW[] ipNetTable = new MIB_IPNETROW[count]; // Get the structure type and size. Type tMIB_IPNETROW = typeof(MIB_IPNETROW); size = Marshal.SizeOf(tMIB_IPNETROW); int dw = Marshal.SizeOf(new int()); // 4-bytes // Cycle through the entries. for (int index = 0; index < count; index++) { // Call PtrToStructure, getting the structure information. ipNetTable[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(pBuffer.ToInt64() + dw + (index * size)), tMIB_IPNETROW); } return(ipNetTable); } finally { // Release the allocate the memory buffer. if (pBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(pBuffer); } } }
private static Dictionary <IPAddress, PhysicalAddress> GetAllDevicesOnLAN() { Dictionary <IPAddress, PhysicalAddress> all = new Dictionary <IPAddress, PhysicalAddress>(); all.Add(GetIPAddress(), GetMacAddress()); int spaceForNetTable = 0; GetIpNetTable(IntPtr.Zero, ref spaceForNetTable, false); IntPtr rawTable = IntPtr.Zero; try { rawTable = Marshal.AllocCoTaskMem(spaceForNetTable); int errorCode = GetIpNetTable(rawTable, ref spaceForNetTable, false); if (errorCode != 0) { throw new Exception(string.Format( "Unable to retrieve network table. Error code {0}", errorCode)); } int rowsCount = Marshal.ReadInt32(rawTable); IntPtr currentBuffer = new IntPtr(rawTable.ToInt64() + Marshal.SizeOf(typeof(Int32))); MIB_IPNETROW[] rows = new MIB_IPNETROW[rowsCount]; for (int index = 0; index < rowsCount; index++) { rows[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW))) ), typeof(MIB_IPNETROW)); } PhysicalAddress virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }); PhysicalAddress broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }); foreach (MIB_IPNETROW row in rows) { IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); byte[] rawMAC = new byte[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 }; PhysicalAddress pa = new PhysicalAddress(rawMAC); if (!pa.Equals(virtualMAC) && !pa.Equals(broadcastMAC) && !IsMulticast(ip)) { //Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString()); if (!all.ContainsKey(ip)) { all.Add(ip, pa); } } } } finally { // Release the memory. Marshal.FreeCoTaskMem(rawTable); } return(all); }
/// <summary> /// Liste des entrées de la table ARP. /// </summary> public IEnumerable <ArpEntry> GetArpEntries() { List <ArpEntry> arpEntries = new List <ArpEntry>(); IntPtr pTable = IntPtr.Zero; int iBufLen = 0; int iRet = 0; //1ier appel pour déterminer la taille de la table ARP. iRet = NativeMethods.GetIpNetTable(IntPtr.Zero, ref iBufLen, true); try { pTable = Marshal.AllocHGlobal(iBufLen); //Lecture de la table. iRet = NativeMethods.GetIpNetTable(pTable, ref iBufLen, true); //Retour OK. if (iRet == 0) { //Nombre d'entrées dans la table. int iEntries = Marshal.ReadInt32(pTable); //Pointeur sur 1ière entrée. IntPtr pEntry = new IntPtr(pTable.ToInt32() + 4); //Parcours chaque entrée. for (int i = 0; i < iEntries; i++) { //Lit l'entrée. MIB_IPNETROW entry = (MIB_IPNETROW)Marshal.PtrToStructure(pEntry, typeof(MIB_IPNETROW)); ArpEntry arpEntry = new ArpEntry(_adapters.GetAdapter(entry.dwIndex), entry.bPhysAddr, entry.dwAddr, entry.dwType); arpEntry._ipArpNative = entry; //Extrait les infos. arpEntries.Add(arpEntry); //Pointeur sur entrée suivante. pEntry = new IntPtr(pEntry.ToInt32() + Marshal.SizeOf(typeof(MIB_IPNETROW))); } } } catch (Exception) { } finally { Marshal.FreeHGlobal(pTable); } return(arpEntries); }
private static string MACToString(MIB_IPNETROW row) { var sb = new StringBuilder(); sb.Append(ByteToHexString(row.mac0)); sb.Append(":"); sb.Append(ByteToHexString(row.mac1)); sb.Append(":"); sb.Append(ByteToHexString(row.mac2)); sb.Append(":"); sb.Append(ByteToHexString(row.mac3)); sb.Append(":"); sb.Append(ByteToHexString(row.mac4)); sb.Append(":"); sb.Append(ByteToHexString(row.mac5)); return(sb.ToString()); }
private MIB_IPNETROW[] GetPhysicalAddressTable() { int bytesNeeded = 0; int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); if (result != INSUFFICIENT_BUFFER) { throw new ApplicationException(Convert.ToString(result)); } IntPtr buffer = IntPtr.Zero; MIB_IPNETROW[] table; try { buffer = Marshal.AllocCoTaskMem(bytesNeeded); result = GetIpNetTable(buffer, ref bytesNeeded, false); if (result != 0) { throw new ApplicationException(Convert.ToString(result)); } int entries = Marshal.ReadInt32(buffer); IntPtr currentBuffer = new IntPtr(buffer.ToInt64() + sizeof(int)); table = new MIB_IPNETROW[entries]; for (int i = 0; i < entries; i++) { table[i] = (MIB_IPNETROW)Marshal.PtrToStructure( new IntPtr(currentBuffer.ToInt64() + (i * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW) ); } } finally { Marshal.FreeCoTaskMem(buffer); } return(table); }
public void PrintAddressesWithMac() { MIB_IPNETROW[] table = GetMibIpNetRowArray(); //for (int index = 0; index < entries; index++) for (int index = 0; index < table.Length; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); Console.Write("IP:" + ip.ToString() + "\t\tMAC:"); Console.Write(row.mac0.ToString("X2") + '-'); Console.Write(row.mac1.ToString("X2") + '-'); Console.Write(row.mac2.ToString("X2") + '-'); Console.Write(row.mac3.ToString("X2") + '-'); Console.Write(row.mac4.ToString("X2") + '-'); Console.WriteLine(row.mac5.ToString("X2")); } }
public static byte[] GetCachedAddress(string address) { RefreshCache(); byte[] cachedAddress = new byte[] { }; // Finally, the try block // Choose to access the cache array outside of the above loop for ease of access. // There should be no issue in doing all of this in one loop. for (int i = 0; i < numberOfEntries; i++) { MIB_IPNETROW row = cache[i]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); if (ip.ToString() == address) { cachedAddress = new byte[] { row.macByte0, row.macByte1, row.macByte2, row.macByte3, row.macByte4, row.macByte5 }; } } return(cachedAddress); }
public static void FlushFreezeArp(int adapterIndex, string adapterGateway) { byte[] gateway = GetCachedAddress(adapterGateway); MIB_IPNETROW staticRouter = new MIB_IPNETROW(); staticRouter.dwIndex = adapterIndex; staticRouter.dwPhysAddrLen = 6; staticRouter.macByte0 = gateway[0]; staticRouter.macByte1 = gateway[1]; staticRouter.macByte2 = gateway[2]; staticRouter.macByte3 = gateway[3]; staticRouter.macByte4 = gateway[4]; staticRouter.macByte5 = gateway[5]; staticRouter.macByte6 = 0; staticRouter.macByte7 = 0; staticRouter.dwAddr = BitConverter.ToInt32(IPAddress.Parse(adapterGateway).GetAddressBytes(), 0); staticRouter.dwType = 4; FlushIpNetTable(adapterIndex); CreateIpNetEntry(staticRouter); }
public static List <IPInfo2> GetIPInfo() { int bytesNeeded = 0; int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); if (result != ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } IntPtr buffer = IntPtr.Zero; try { buffer = Marshal.AllocCoTaskMem(bytesNeeded); result = GetIpNetTable(buffer, ref bytesNeeded, false); if (result != 0) { throw new Win32Exception(result); } int count = Marshal.ReadInt32(buffer); var currentBuffer = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(int))); var table = new List <IPInfo2>(); for (int i = 0; i < count; i++) { MIB_IPNETROW row = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (i * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); table.Add(new IPInfo2(MACToString(row), new IPAddress(BitConverter.GetBytes(row.dwAddr)).ToString())); } return(table); } finally { FreeMibTable(buffer); } }
public static List <ARPInfo> GetTable() { var list = new List <ARPInfo>(); // The number of bytes needed. var bytesNeeded = 0; // The result from the API call. var result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. var buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. var table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (var i = 0; i < entries; i++) { // Call PtrToStructure, getting the structure information. table[i] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (i * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } var virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }); var broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }); for (var i = 0; i < entries; i++) { var row = table[i]; var ipAddress = new IPAddress(BitConverter.GetBytes(row.dwAddr)); var macAddress = new PhysicalAddress(new[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 }); // Filter 0.0.0.0.0.0, 255.255.255.255.255.255 if (!macAddress.Equals(virtualMAC) && !macAddress.Equals(broadcastMAC)) { list.Add(new ARPInfo(ipAddress, macAddress, ipAddress.IsIPv6Multicast || IPv4Address.IsMulticast(ipAddress))); } } return(list); } finally { // Release the memory. FreeMibTable(buffer); } }
public static async Task <List <IPAddress> > CheckARPTableAsync(bool onlyQuests = true) { int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Exception(); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. // Allocate the memory. IntPtr buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Exception(); } // 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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } List <IPAddress> ips = new List <IPAddress>(); for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; if (!onlyQuests || (row.mac0 == 0x2C && row.mac1 == 0x26 && row.mac2 == 0x17)) { IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); if (!ips.Contains(ip)) { ips.Add(ip); } } } // Release the memory. FreeMibTable(buffer); return(ips); }
public static List <(string IpAddress, string Mac)> GetArpTable() { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } IntPtr buffer = IntPtr.Zero; try { // Allocate the memory, do it in a try/finally block, to ensure // that it is released. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } var list = new List <(string IpAddress, string Mac)>(); for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; //Obtain IP address System.Net.IPAddress ip = new System.Net.IPAddress(BitConverter.GetBytes(table[index].dwAddr)); //Build MAC string mac = row.mac0.ToString("X2") + '-' + row.mac1.ToString("X2") + '-' + row.mac2.ToString("X2") + '-' + row.mac3.ToString("X2") + '-' + row.mac4.ToString("X2") + '-' + row.mac5.ToString("X2"); //Add return value list.Add((ip.ToString(), mac)); } return(list); } finally { // Release the memory. FreeMibTable(buffer); } }
static string[] searchIpsFromMac(string macSearched) { List <string> ips = new List <string>(1); // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); string macAddr = row.mac0.ToString("X2") + '-' + row.mac1.ToString("X2") + '-' + row.mac2.ToString("X2") + '-' + row.mac3.ToString("X2") + '-' + row.mac4.ToString("X2") + '-' + row.mac5.ToString("X2"); if (macAddr.ToUpper() == macSearched.ToUpper()) { ips.Add(ip.ToString()); } } } finally { // Release the memory. FreeMibTable(buffer); } return(ips.ToArray()); }
public static String getMacFromARPwithIP(String IP) { String mac = null; // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } for (int index = 0; index < entries; index++) { IPAddress ip = new IPAddress(BitConverter.GetBytes(table[index].dwAddr)); if (ip.ToString().Equals(IP)) { byte b; b = table[index].mac0; if (b < 0x10) { mac = "0"; //Console.Write("0"); } else { mac = ""; Console.Write(""); } mac += b.ToString("X"); Console.Write(b.ToString("X")); b = table[index].mac1; if (b < 0x10) { mac += "-0"; } else { mac += "-"; } mac += b.ToString("X"); b = table[index].mac2; if (b < 0x10) { mac += "-0"; } else { mac += "-"; } mac += b.ToString("X"); b = table[index].mac3; if (b < 0x10) { mac += "-0"; } else { mac += "-"; } mac += b.ToString("X"); b = table[index].mac4; if (b < 0x10) { mac += "-0"; } else { mac += "-"; } mac += b.ToString("X"); b = table[index].mac5; if (b < 0x10) { mac += "-0"; } else { mac += "-"; } mac += b.ToString("X"); } } } finally { // Release the memory. Marshal.FreeCoTaskMem(buffer); } return(mac); }
internal static extern int DeleteIpNetEntry(MIB_IPNETROW pArpEntry);
static void Main(string[] args) { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); Console.Write("IP:" + ip.ToString() + "\t\tMAC:"); Console.Write(row.mac0.ToString("X2") + '-'); Console.Write(row.mac1.ToString("X2") + '-'); Console.Write(row.mac2.ToString("X2") + '-'); Console.Write(row.mac3.ToString("X2") + '-'); Console.Write(row.mac4.ToString("X2") + '-'); Console.Write(row.mac5.ToString("X2") + "\t"); Console.WriteLine((row.mac3 << 16) + (row.mac4 << 8) + row.mac5); } } finally { // Release the memory. FreeMibTable(buffer); } Console.ReadKey(); // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app! }
public override CommandResult Execute(CommandResult pipeIn) { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { throw new NoPowerShellException("Error in execution: {0}", result); } // Allocate the memory, do it in a try/finally block, to ensure that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { throw new NoPowerShellException("Error in execution: {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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure( new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW) ); } // Iterate over records and add them to cmdlet result for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); ARPType type = (ARPType)row.dwType; _results.Add( new ResultRecord() { { "ifIndex", row.dwIndex.ToString() }, { "IPAddress", ip.ToString() }, { "LinkLayerAddress", string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5) }, { "State", type.ToString() } } ); } } finally { // Release the memory. FreeMibTable(buffer); } return(_results); }
/// <summary> /// Get the IP and MAC addresses of all known devices on the LAN /// </summary> /// <remarks> /// 1) This table is not updated often - it can take some human-scale time /// to notice that a device has dropped off the network, or a new device /// has connected. /// 2) This discards non-local devices if they are found - these are multicast /// and can be discarded by IP address range. /// </remarks> /// <returns></returns> private static Dictionary<IPAddress, PhysicalAddress> GetAllDevicesOnLAN() { var all = new Dictionary<IPAddress, PhysicalAddress>(); // Add this PC to the list... all.Add(GetIPAddress(), GetMacAddress()); var spaceForNetTable = 0; // Get the space needed // We do that by requesting the table, but not giving any space at all. // The return value will tell us how much we actually need. GetIpNetTable(IntPtr.Zero, ref spaceForNetTable, false); // Allocate the space // We use a try-finally block to ensure release. var rawTable = IntPtr.Zero; try { rawTable = Marshal.AllocCoTaskMem(spaceForNetTable); // Get the actual data var errorCode = GetIpNetTable(rawTable, ref spaceForNetTable, false); if (errorCode != 0) { // Failed for some reason - can do no more here. throw new Exception(string.Format( "Unable to retrieve network table. Error code {0}", errorCode)); } // Get the rows count var rowsCount = Marshal.ReadInt32(rawTable); var currentBuffer = new IntPtr(rawTable.ToInt64() + Marshal.SizeOf(typeof (int))); // Convert the raw table to individual entries var rows = new MIB_IPNETROW[rowsCount]; for (var index = 0; index < rowsCount; index++) { rows[index] = (MIB_IPNETROW) Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + index* Marshal.SizeOf(typeof (MIB_IPNETROW)) ), typeof (MIB_IPNETROW)); } // Define the dummy entries list (we can discard these) var virtualMAC = new PhysicalAddress(new byte[] {0, 0, 0, 0, 0, 0}); var broadcastMAC = new PhysicalAddress(new byte[] {255, 255, 255, 255, 255, 255}); foreach (var row in rows) { var ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); byte[] rawMAC = {row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5}; var pa = new PhysicalAddress(rawMAC); if (!pa.Equals(virtualMAC) && !pa.Equals(broadcastMAC) && !IsMulticast(ip)) { //Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString()); if (!all.ContainsKey(ip)) { all.Add(ip, pa); } } } } finally { // Release the memory. Marshal.FreeCoTaskMem(rawTable); } return all; }
public static string GetMac(string givenIp) { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); /* Console.Write("IP:" + ip.ToString() + "\t\tMAC:"); * * Console.Write(row.mac0.ToString("X2") + '-'); * Console.Write(row.mac1.ToString("X2") + '-'); * Console.Write(row.mac2.ToString("X2") + '-'); * Console.Write(row.mac3.ToString("X2") + '-'); * Console.Write(row.mac4.ToString("X2") + '-'); * Console.WriteLine(row.mac5.ToString("X2")); */ if (ip.ToString() == givenIp) { FreeMibTable(buffer); // Console.WriteLine(ip.ToString()); string output = row.mac0.ToString("X2") + '-' + row.mac1.ToString("X2") + '-' + row.mac2.ToString("X2") + '-' + row.mac3.ToString("X2") + '-' + row.mac4.ToString("X2") + '-' + row.mac5.ToString("X2"); return(output); } } // Release the memory. FreeMibTable(buffer); } catch (Exception e) { Console.WriteLine("GetMac: Exception " + e); } return(null); }
public extern static int SetIpNetEntry(ref MIB_IPNETROW pArpEntry);
public extern static int CreateIpNetEntry(ref MIB_IPNETROW pArpEntry);
static void Main(string[] args) { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); Console.Write("IP:" + ip.ToString() + "\t\tMAC:"); Console.Write(row.mac0.ToString("X2") + '-'); Console.Write(row.mac1.ToString("X2") + '-'); Console.Write(row.mac2.ToString("X2") + '-'); Console.Write(row.mac3.ToString("X2") + '-'); Console.Write(row.mac4.ToString("X2") + '-'); Console.Write(row.mac5.ToString("X2")); Console.Write("\t\tType:{0}",GetTypeOfEntry(row.dwType)); Console.WriteLine(); } Console.ReadKey(); } finally { // Release the memory. FreeMibTable(buffer); } }
/// <summary> /// Get the IP and MAC addresses of all known devices on the LAN /// </summary> /// <remarks> /// 1) This table is not updated often - it can take some human-scale time /// to notice that a device has dropped off the network, or a new device /// has connected. /// 2) This discards non-local devices if they are found - these are multicast /// and can be discarded by IP address range. /// </remarks> /// <returns></returns> public static Dictionary <IPAddress, PhysicalAddress> GetAllDevicesOnLan() { var all = new Dictionary <IPAddress, PhysicalAddress> { { GetIPAddress(), GetMacAddress() } }; // Add this PC to the list... var spaceForNetTable = 0; // Get the space needed // We do that by requesting the table, but not giving any space at all. // The return value will tell us how much we actually need. GetIpNetTable(IntPtr.Zero, ref spaceForNetTable, false); // Allocate the space // We use a try-finally block to ensure release. var rawTable = IntPtr.Zero; try { rawTable = Marshal.AllocCoTaskMem(spaceForNetTable); // Get the actual data var errorCode = GetIpNetTable(rawTable, ref spaceForNetTable, false); if (errorCode != 0) { // Failed for some reason - can do no more here. throw new Exception($"Unable to retrieve network table. Error code {errorCode}"); } // Get the rows count var rowsCount = Marshal.ReadInt32(rawTable); var currentBuffer = new IntPtr(rawTable.ToInt64() + Marshal.SizeOf(typeof(int))); // Convert the raw table to individual entries var rows = new MIB_IPNETROW[rowsCount]; for (var index = 0; index < rowsCount; index++) { rows[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + index * Marshal.SizeOf(typeof(MIB_IPNETROW)) ), typeof(MIB_IPNETROW)); } // Define the dummy entries list (we can discard these) var virtualMac = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }); var broadcastMac = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }); foreach (var row in rows) { var ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); var rawMac = new[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 }; var pa = new PhysicalAddress(rawMac); if (pa.Equals(virtualMac) || pa.Equals(broadcastMac) || IsMulticast(ip)) { continue; } //Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString()); if (!all.ContainsKey(ip)) { all.Add(ip, pa); } } } finally { // Release the memory. Marshal.FreeCoTaskMem(rawTable); } return(all); }
static void Main(string[] args) { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } uint _arpInt = 0; for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); // check to see if we printed a new interface // if so print like `arp -av` output if (_arpInt != row.dwIndex) { // prior row dwindex does NOT match so its same interface Console.WriteLine($"Interface: INT: {row.dwIndex.ToString()} --- TYPE: {row.dwType} --- IP: {ip.ToString()}"); } string pP = string.Format("\t{0,-20}{1,0}{2,-2}{3,0}{4,0}{5,0}{6,0}", ip.ToString(), row.mac0.ToString("X2") + '-', row.mac1.ToString("X2") + '-', row.mac2.ToString("X2") + '-', row.mac3.ToString("X2") + '-', row.mac4.ToString("X2") + '-', row.mac5.ToString("X2")); _arpInt = row.dwIndex; Console.WriteLine(pP); } } finally { // Release the memory. FreeMibTable(buffer); } }
public static List <ARP> StartAudit() { List <ARP> lstArp = new List <ARP>(); try { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. return(lstArp); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. return(lstArp); } // 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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); Dictionary <int, string> adapterNameAndIndex = PrintInterfaceIndex(); for (int index = 0; index < entries; index++) { ARP oarp = new ARP(); MIB_IPNETROW row = table[index]; if (adapterNameAndIndex.ContainsKey(row.dwIndex)) { oarp.Interface = adapterNameAndIndex[row.dwIndex]; } else { oarp.Interface = row.dwIndex.ToString(); } IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); oarp.IP4Address = ip.ToString(); StringBuilder mac = new StringBuilder(); mac.Append(row.mac0.ToString("X2")); mac.Append(row.mac0.ToString("-")); mac.Append(row.mac1.ToString("X2")); mac.Append(row.mac1.ToString("-")); mac.Append(row.mac2.ToString("X2")); mac.Append(row.mac2.ToString("-")); mac.Append(row.mac3.ToString("X2")); mac.Append(row.mac3.ToString("-")); mac.Append(row.mac4.ToString("X2")); oarp.PhysicalAddress = mac.ToString(); oarp.CacheType = ((dwTypes)row.dwType).ToString(); lstArp.Add(oarp); } } finally { // Release the memory. FreeMibTable(buffer); } } catch (Exception) { throw; // //logger.Error(ex); } return(lstArp); }
private MIB_IPNETROW[] GetMibIpNetRowArray() { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } return(table); } finally { // Release the memory. FreeMibTable(buffer); } }
static void Main(string[] args) { // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } Console.WriteLine("\n Internet Address Physical Address Type"); for (int index = 0; index < entries; index++) { MIB_IPNETROW row = table[index]; IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); string[] mac_arr = { row.mac0.ToString("X2"), row.mac1.ToString("X2"), row.mac2.ToString("X2"), row.mac3.ToString("X2"), row.mac4.ToString("X2"), row.mac5.ToString("X2") }; string ip_str = String.Format("{0,-22}", ip.ToString()); string mac_str = String.Format("{0,-22}", string.Join("-", mac_arr)); string type = "static"; if (mac_str == "00-00-00-00-00-00 ") { continue; } if (row.dwType == 3) { type = "dynamic"; } Console.WriteLine(" " + ip_str + mac_str + type); } } finally { // Release the memory. FreeMibTable(buffer); } Console.WriteLine("\nDONE"); }
private MIB_IPNETROW[] GetPhysicalAddressTable() { int bytesNeeded = 0; int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); if (result != INSUFFICIENT_BUFFER) { throw new ApplicationException(Convert.ToString(result)); } IntPtr buffer = IntPtr.Zero; MIB_IPNETROW[] table; try { buffer = Marshal.AllocCoTaskMem(bytesNeeded); result = GetIpNetTable(buffer, ref bytesNeeded, false); if (result != 0) { throw new ApplicationException(Convert.ToString(result)); } int entries = Marshal.ReadInt32(buffer); IntPtr currentBuffer = new IntPtr(buffer.ToInt64() + sizeof (int)); table = new MIB_IPNETROW[entries]; for (int i = 0; i < entries; i++) { table[i] = (MIB_IPNETROW)Marshal.PtrToStructure( new IntPtr(currentBuffer.ToInt64() + (i * Marshal.SizeOf(typeof (MIB_IPNETROW)))), typeof (MIB_IPNETROW) ); } } finally { Marshal.FreeCoTaskMem(buffer); } return table; }
public static void GetNames(IP_Code.LocalHost LocalHost) { // 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 an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. table[index] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } for (int index = 0; index < entries; index++) { IPAddress ip = new IPAddress((table[index].dwAddr & 0xFFFFFFFF)); Console.Write("IP:" + ip.ToString() + "\t\tMAC:"); ipstr = ip.ToString(); macname = "MAC:"; byte b; b = table[index].mac0; if (b < 0x10) { Console.Write("0"); macname = macname + "0"; } else { Console.Write(""); } Console.Write(b.ToString("X")); macname = macname + b.ToString("X"); b = table[index].mac1; if (b < 0x10) { Console.Write("-0"); macname = macname + "-0"; } else { Console.Write("-"); macname = macname + "-"; } Console.Write(b.ToString("X")); macname = macname + b.ToString("X"); b = table[index].mac2; if (b < 0x10) { Console.Write("-0"); macname = macname + "-0"; } else { Console.Write("-"); macname = macname + "-"; } Console.Write(b.ToString("X")); macname = macname + b.ToString("X"); b = table[index].mac3; if (b < 0x10) { Console.Write("-0"); macname = macname + "-0"; } else { Console.Write("-"); macname = macname + "-"; } Console.Write(b.ToString("X")); macname = macname + b.ToString("X"); b = table[index].mac4; if (b < 0x10) { Console.Write("-0"); macname = macname + "-0"; } else { Console.Write("-"); macname = macname + "-"; } Console.Write(b.ToString("X")); macname = macname + b.ToString("X"); b = table[index].mac5; if (b < 0x10) { Console.Write("-0"); macname = macname + "-0"; } else { Console.Write("-"); macname = macname + "-"; } Console.Write(b.ToString("X")); macname = macname + b.ToString("X"); Console.WriteLine(); //test for device if (table[index].mac0 == 0x00 && table[index].mac1 == 0x00 && table[index].mac2 == 0x00) { //if device matches } } }