C#检索局域网内主机的IP、MAC地址

  本文代码(绝对的完整)来源于网络,供大家参考学习,感谢各位大佬!(备注:亲测代码运行效率可保证!

1 第一种方法(Ping方法)

  由于每次Ping IP的结果不同,故程序每次运行结果可能不一样。完整代码如下:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;

namespace testCodes0313
{
    class Program
    {
        static List<string> ips = new List<string>();
        static void Main(string[] args)
        {
            GetIPAddress();
            foreach (var ip in ips)
            {
                Console.WriteLine(ip);
            }
            Console.ReadKey();
        }

        static void GetIPAddress()
        {
            string myHostName = Dns.GetHostName();//本机名
            string myHostIP = Dns.GetHostEntry(myHostName).AddressList[1].ToString();//本机IP地址
            string IpRange = myHostIP.Remove(myHostIP.LastIndexOf('.'));//IP网段
            for(int r = 1; r <= 255; r++)//枚举网段计算机
            {
                Ping ping = new Ping();
                ping.PingCompleted += new PingCompletedEventHandler(ping_Completed);//事件绑定方法
                string pingIP = IpRange + "." + r.ToString();
                ping.SendAsync(pingIP, 1000, null);
            }
        }

        static void ping_Completed(object sender,PingCompletedEventArgs e)
        {
            if (e.Reply.Status == IPStatus.Success)
            {
                ips.Add(e.Reply.Address.ToString());
            }
        }
    }
}

2 第二种方法(某大佬方法)

  不明觉厉,很大佬的方法(原文链接),点赞!完整代码如下:


using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;

namespace LanIps
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
			
			// TODO: Implement Functionality Here
			// Get my PC IP address
			Console.WriteLine("My IP : {0}", GetIPAddress());
			// Get My PC MAC address
			Console.WriteLine("My MAC: {0}", GetMacAddress());
			// Get My PC HostName
			Console.WriteLine("My HostName: {0}", Dns.GetHostName());
			// Get all devices on network
			Dictionary<IPAddress, PhysicalAddress> all = GetAllDevicesOnLAN();
			foreach (KeyValuePair<IPAddress, PhysicalAddress> kvp in all)
			{
				Console.WriteLine("IP : {0}\n MAC {1}", kvp.Key, kvp.Value);
			}
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
		
		/// <summary>
		/// MIB_IPNETROW structure returned by GetIpNetTable
		/// DO NOT MODIFY THIS STRUCTURE.
		/// </summary>
		[StructLayout(LayoutKind.Sequential)]
		struct MIB_IPNETROW
		{
			[MarshalAs(UnmanagedType.U4)]
			public int dwIndex;
			[MarshalAs(UnmanagedType.U4)]
			public int dwPhysAddrLen;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac0;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac1;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac2;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac3;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac4;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac5;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac6;
			[MarshalAs(UnmanagedType.U1)]
			public byte mac7;
			[MarshalAs(UnmanagedType.U4)]
			public int dwAddr;
			[MarshalAs(UnmanagedType.U4)]
			public int dwType;
		}

		/// <summary>
		/// GetIpNetTable external method
		/// </summary>
		/// <param name="pIpNetTable"></param>
		/// <param name="pdwSize"></param>
		/// <param name="bOrder"></param>
		/// <returns></returns>
		[DllImport("IpHlpApi.dll")]
		[return: MarshalAs(UnmanagedType.U4)]
		static extern int GetIpNetTable(IntPtr pIpNetTable,
		                                [MarshalAs(UnmanagedType.U4)] ref int pdwSize, bool bOrder);

		/// <summary>
		/// Error codes GetIpNetTable returns that we recognise
		/// </summary>
		const int ERROR_INSUFFICIENT_BUFFER = 122;
		/// <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()
		{
			Dictionary<IPAddress, PhysicalAddress> all = new Dictionary<IPAddress, PhysicalAddress>();
			// Add this PC to the list...
			all.Add(GetIPAddress(), GetMacAddress());
			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) && !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>
		/// Gets the IP address of the current PC
		/// </summary>
		/// <returns></returns>
		private static IPAddress GetIPAddress()
		{
			String strHostName = Dns.GetHostName();
			IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
			IPAddress[] addr = ipEntry.AddressList;
			foreach (IPAddress ip in addr)
			{
				if (!ip.IsIPv6LinkLocal)
				{
					return (ip);
				}
			}
			return addr.Length > 0 ? addr[0] : null;
		}

		/// <summary>
		/// Gets the MAC address of the current PC.
		/// </summary>
		/// <returns></returns>
		private static PhysicalAddress GetMacAddress()
		{
			foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
			{
				// Only consider Ethernet network interfaces
				if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
				    nic.OperationalStatus == OperationalStatus.Up)
				{
					return nic.GetPhysicalAddress();
				}
			}
			return null;
		}

		/// <summary>
		/// Returns true if the specified IP address is a multicast address
		/// </summary>
		/// <param name="ip"></param>
		/// <returns></returns>
		private static bool IsMulticast(IPAddress ip)
		{
			bool result = true;
			if (!ip.IsIPv6Multicast)
			{
				byte highIP = ip.GetAddressBytes()[0];
				if (highIP < 224 || highIP > 239)
				{
					result = false;
				}
			}
			return result;
		}
	}
}

  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C_xxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值