using System.Net; using System.Net.NetworkInformation; using System.Runtime.InteropServices; namespace NWService { public class NetworkService { [DllImport("iphlpapi.dll", ExactSpelling = true)] private static extern int SendARP(int dstIp, int srcIp, byte[] mac, ref int macLen); public static PingReply Ping(IPAddress iPAddress) { using (Ping ping = new Ping()) { PingReply reply = ping.Send(iPAddress); return reply; } } public static List SearchByPing(IPAddress targetIPv4) { int workThreadsMin; int ioThreadsMin; ThreadPool.GetMinThreads(out workThreadsMin, out ioThreadsMin); ThreadPool.SetMinThreads(260, ioThreadsMin); List avaIPs = new List(); List allTasks = new List(); for (int i = 1 ; i <= 254 ; i++) { int hostPart = i; allTasks.Add(Task.Run(() => { List separateIP = targetIPv4.ToString().Split('.').ToList(); separateIP.RemoveAt(3); separateIP.Add(hostPart.ToString()); string networkPart = string.Join(".", separateIP); PingReply reply = Ping(IPAddress.Parse(networkPart)); if (reply != null && reply.Status == IPStatus.Success) { avaIPs.Add(reply); } })); } Task t = Task.WhenAll(allTasks); try { t.Wait(); } catch(Exception error) { Console.WriteLine(error); } return avaIPs; } public static List SearchARP(IPAddress targetIPv4) { int workThreadsMin; int ioThreadsMin; ThreadPool.GetMinThreads(out workThreadsMin, out ioThreadsMin); ThreadPool.SetMinThreads(260, ioThreadsMin); List avaIPs = new List(); List allTasks = new List(); for (int i = 1 ; i <= 254; i++) { int hostPart = i; allTasks.Add(Task.Run(() => { List separateIP = targetIPv4.ToString().Split('.').ToList(); separateIP.RemoveAt(3); separateIP.Add(hostPart.ToString()); string networkPart = string.Join(".", separateIP); int IPBytes = BitConverter.ToInt32(IPAddress.Parse(networkPart).GetAddressBytes(), 0); byte[] macAddressPointer = new byte[6]; int physicalAddressLength = macAddressPointer.Length; // ARP int ret = SendARP(IPBytes, 0, macAddressPointer, ref physicalAddressLength); if (ret == 0) { DeviceInfo info = new DeviceInfo(IPAddress.Parse(networkPart), macAddressPointer); avaIPs.Add(info); } })); } Task t = Task.WhenAll(allTasks); try { t.Wait(); } catch(Exception error) { Console.WriteLine(error); } return avaIPs; } public static IEnumerable GetLocalIPv4() { List list = new List(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { if (nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback && nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel) { UnicastIPAddressInformationCollection unicast = nic.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation ip in unicast) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { list.Add(ip.Address); } } } } return list; } } }