C#扫描IP
通过Dns类获得本机IP,可能有多个,通过这个得到子网掩码,默认前24位为1
private void IPScan()
{
string myHostName = Dns.GetHostName();
IPAddress[] IPList = Dns.GetHostEntry(myHostName).AddressList;
this.listBox.Items.Add("HostName:"+myHostName);
for (int i = 0; i < IPList.Length; i++)
{
if (IPList[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
this.listBox.Items.Add(IPList[i].ToString());
PingIP(IPList[i]);
}
}
}
然后把此段类的IP地址通过Ping类都ping一遍,能ping通再通过SendARP获取目的主机的MAC地址
private void PingIP(IPAddress ipa)
{
byte[] ipByte = ipa.GetAddressBytes();
string ipComm = ipByte[0] + "." + ipByte[1] + "." + ipByte[2] + ".";
string pingIP = "";
for (int lastByte = 0; lastByte <= 255; lastByte++)
{
Ping ping = new Ping();
ping.PingCompleted += new PingCompletedEventHandler(PingComplete);
pingIP = ipComm + lastByte;
ping.SendAsync(pingIP, 2000, null);
}
}
[DllImport(@"iphlpapi.dll", ExactSpelling = true)]
private static extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);
private void PingComplete(object sender, PingCompletedEventArgs e)
{
if (e.Reply.Status == IPStatus.Success)
{
IPAddress ip = e.Reply.Address;
this.listBox.Items.Add("IP:" + ip.ToString());
byte[] b = new byte[6];
int len = b.Length;
int r = SendARP(BitConverter.ToInt32(ip.GetAddressBytes(), 0), 0, b, ref len);
string mac = BitConverter.ToString(b, 0, 6);
this.listBox.Items.Add("Mac:" + mac);
}
}
如果要获取子网掩码,就需要用到命名空间System.Manaement里面的类
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection nics = mc.GetInstances();
foreach (ManagementObject nic in nics)
{
if (Convert.ToBoolean(nic["ipEnabled"]) == true)
{
string mac = nic["MacAddress"].ToString();//Mac地址
string ip = (nic["IPAddress"] as String[])[0];//IP地址
string ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码
string ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关
}
}
这种方式是或得系统进程,从进程里面读取信息
当然,还有一种获得本机IP的方法
更简洁
string hostName = Dns.GetHostName();
IPHostEntry iPHostEntry = Dns.GetHostEntry(hostName);
var addressV = iPHostEntry.AddressList.FirstOrDefault(q => q.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
strin ip = Convert.ToString(addressV);
希望可用帮助你,喜欢点个赞呗