C#获取局域网主机
最近在做一个使用MSRDPClient来实现远程桌面功能,需要先判断一下该局域网主机是否在线,所以就需要获取一遍局域网主机。
首先获取本地IP地址,这里需要注意的是,要排除掉虚拟机的IP,实现代码如下:
public List<string> GetLocalIPs()
{
List<string> lstIp = new List<string>();
ManagementClass mcNetworkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc_NetworkAdapterConfig = mcNetworkAdapterConfig.GetInstances();
foreach(ManagementObject mo in moc_NetworkAdapterConfig)
{
string mServiceName = mo["ServiceName"] as string;
if (!(bool)mo["IPEnabled"])
{
continue;
}
mServiceName = mServiceName.ToLower();
if(mServiceName.Contains("vmnetadapter")
|| mServiceName.Contains("ppoe")
|| mServiceName.Contains("bthpan")
|| mServiceName.Contains("tapvpn")
|| mServiceName.Contains("ndisip")
|| mServiceName.Contains("sinforvnic"))
{
continue;
}
string mCaption = mo["Caption"] as string;
string mMACAddress = mo["MACAddress"] as string;
string[] mIPAddress = mo["IPAddress"] as string[];
string[] mIPSubnet = mo["IPSubnet"] as string[];
string[] mDefaultIPGateway = mo["DefaultIPGateway"] as string[];
string[] mDNSServerSearchOrder = mo["DNSServerSearchOrder"] as string[];
if(mIPAddress != null)
{
foreach(string ip in mIPAddress)
{
if(ip != "0.0.0.0")
{
if(IPAddress.TryParse(ip, out IPAddress address))
{
if(address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)//排除IP6地址,根据实际情况排除
{
lstIp.Add(ip);
}
}
}
}
}
mo.Dispose();
}
return lstIp;
}
然后采用Ping主机,查看是否有返回,实现代码如下:
public void GetLANIps()
{
this.count = 1;
this.IsOk = false;
this.IPHosts.Clear();
string localHostIp = this.LocalIps[0];
string ipDuan = localHostIp.Remove(localHostIp.LastIndexOf('.'));
byte[] bys = Encoding.UTF8.GetBytes("hello");
for (int i = 1; i <= 255; i++)
{
string pingIp = $"{ipDuan}.{i}";
Ping ping = new Ping();
ping.PingCompleted += Ping_PingCompleted;
ping.SendAsync(pingIp, 200, bys);
}
}
private void Ping_PingCompleted(object sender, PingCompletedEventArgs e)
{
if(this.count++ == 255)
{
this.IsOk = true;
}
if (e.Reply.Status == IPStatus.Success)
{
try
{
IPHostEntry iPHost = Dns.GetHostEntry(e.Reply.Address);
this.IPHosts.Add(iPHost);
}
catch
{
}
}
}
开个后台线程去获取,这个获取局域网主机不是特别快