Этот код на C# реализует утилиту для обнаружения устройств в локальной сети. Он основывается на принципах ARP (Address Resolution Protocol), используемых для соответствия IP-адресов и MAC-адресов в сети. Программа выполняет следующие действия:
Думаю кому-то будет полезно.
- Извлекает список активных сетевых интерфейсов и их IP-адресов в локальной сети.
- Для каждого IP-адреса выполняет запрос к ARP-кэшу операционной системы, чтобы получить соответствующий MAC-адрес.
- Собирает информацию об IP и MAC-адресах устройств и выводит ее в консоль.
Думаю кому-то будет полезно.
C#:
using System.Collections.Generic;
using System.Linq;
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
public class DeviceInfo
{
public string IP { get; set; }
public string MAC { get; set; }
}
public class ARPCache
{
[StructLayout(LayoutKind.Sequential)]
private struct MIB_IPNETROW
{
public int dwIndex;
public int dwPhysAddrLen;
public byte mac0, mac1, mac2, mac3, mac4, mac5;
public int dwAddr;
public int dwType;
}
[DllImport("IpHlpApi.dll")]
private static extern int GetIpNetTable(IntPtr pIpNetTable, ref int pdwSize, bool bOrder);
[DllImport("IpHlpApi.dll", SetLastError = true)]
private static extern int FreeMibTable(IntPtr plpNetTable);
// Add a method to get MAC address by IP address
public string GetMacAddressByIp(IPAddress ip)
{
foreach (var entry in GetArpCache())
{
if (entry.Key.Equals(ip))
{
return entry.Value;
}
}
return null; // IP address not found in ARP cache
}
public Dictionary<IPAddress, string> GetArpCache()
{
Dictionary<IPAddress, string> arpCache = new Dictionary<IPAddress, string>();
int bufferSize = 0;
int result = GetIpNetTable(IntPtr.Zero, ref bufferSize, false);
IntPtr buffer = IntPtr.Zero;
try
{
buffer = Marshal.AllocCoTaskMem(bufferSize);
result = GetIpNetTable(buffer, ref bufferSize, false);
if (result != 0)
{
throw new Exception("Unable to retrieve ARP cache.");
}
int entries = Marshal.ReadInt32(buffer);
IntPtr currentBuffer = new IntPtr(buffer.ToInt64() + 4);
for (int i = 0; i < entries; i++)
{
MIB_IPNETROW row = (MIB_IPNETROW)Marshal.PtrToStructure(currentBuffer, typeof(MIB_IPNETROW));
IPAddress entryIP = new IPAddress(BitConverter.GetBytes(row.dwAddr));
string macAddress = $"{row.mac0:X2}:{row.mac1:X2}:{row.mac2:X2}:{row.mac3:X2}:{row.mac4:X2}:{row.mac5:X2}";
arpCache[entryIP] = macAddress;
currentBuffer = new IntPtr(currentBuffer.ToInt64() + Marshal.SizeOf(typeof(MIB_IPNETROW)));
}
}
finally
{
if (buffer != IntPtr.Zero)
{
FreeMibTable(buffer);
}
}
return arpCache;
}
}
class Program
{
static void Main()
{
List<DeviceInfo> devices = DiscoverDevices();
foreach (var device in devices)
{
Console.WriteLine($"IP: {device.IP}, MAC: {device.MAC}");
}
}
static List<DeviceInfo> DiscoverDevices()
{
List<DeviceInfo> devices = new List<DeviceInfo>();
// Perform ARP scan to discover devices
foreach (var ip in GetLocalIPv4Addresses())
{
PhysicalAddress macAddress = GetMacAddress(ip);
if (macAddress != null)
{
devices.Add(new DeviceInfo { IP = ip.ToString(), MAC = macAddress.ToString() });
}
}
return devices;
}
static IEnumerable<IPAddress> GetLocalIPv4Addresses()
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(netInterface => netInterface.OperationalStatus == OperationalStatus.Up)
.SelectMany(netInterface => netInterface.GetIPProperties().UnicastAddresses)
.Where(ip => ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
.Select(ip => ip.Address);
}
static PhysicalAddress GetMacAddress(IPAddress ip)
{
try
{
var arp = new ARPCache();
var macAddress = arp.GetMacAddressByIp(ip);
return !string.IsNullOrEmpty(macAddress) ? PhysicalAddress.Parse(macAddress) : null;
}
catch (Exception)
{
return null;
}
}
}