在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
this.lstViewEventDetail.Items.Clear();
C#得到局域网内所有主机名,IP地址,MAC地址 private void btnCheck_Click(object sender, EventArgs e) { string ipAddress = this.cboBoxIp.Text.Trim(); Regex rgx = new Regex(@"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"); if (rgx.IsMatch(ipAddress)) { this.labelIpResult.Text = GetName(ipAddress); this.labelMacResult.Text = GetMacAddress(ipAddress); } else { this.labelIpResult.Text = "IP address is not valid."; this.labelMacResult.Text = "No mac result"; } } ///<summary> /// 得到所有局域网内机器名 ///</summary> private void GetAllLocalMachineName() { System.Diagnostics.ProcessStartInfo prcssStrtInfo = new System.Diagnostics.ProcessStartInfo(); prcssStrtInfo.FileName = @"C:\windows\system32\cmd.exe"; prcssStrtInfo.Arguments = @"/c net view > F:\\LanMachineName.txt"; // 将所有局域网机器名输出到文本文件 prcssStrtInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; System.Diagnostics.Process.Start(prcssStrtInfo); } ///<summary> /// 通过Ip地址获得主机名 ///</summary> ///<param name="IpAddress"></param> ///<returns></returns> private string GetName(string IpAddress)//获取指定IP的计算机名称 { string name=""; try { IPHostEntry ipHstEntry = Dns.GetHostByAddress(IpAddress);//传递IP地址\ //IPHostEntry ipHstEntry = Dns.GetHostEntry(IpAddress); name = ipHstEntry.HostName.ToString();//取得主机名 } catch (Exception e) { name = e.Message; } return name; } ///<summary> /// 通过Ip得到MAC地址 ///</summary> ///<param name="IpAddress"></param> ///<returns></returns> private string GetMacAddress(string IpAddress)//得到指定IP的MAC地址 { string macAddress = ""; Int32 ldest = 0; try { ldest = inet_addr(IpAddress); } catch (Exception iperr) { MessageBox.Show(iperr.Message); } Int64 macinfo = new Int64(); Int32 len = 6; try { int res = SendARP(ldest, 0, ref macinfo, ref len); } catch (Exception err) { // throw new Exception("在解析MAC地址过程发生了错误!"); MessageBox.Show(err.Message); } string originalMACAddress = macinfo.ToString("X4"); if (originalMACAddress != "0000" && originalMACAddress.Length == 12) { //合法MAC地址 string mac1, mac2, mac3, mac4, mac5, mac6; mac1 = originalMACAddress.Substring(10, 2); mac2 = originalMACAddress.Substring(8, 2); mac3 = originalMACAddress.Substring(6, 2); mac4 = originalMACAddress.Substring(4, 2); mac5 = originalMACAddress.Substring(2, 2); mac6 = originalMACAddress.Substring(0, 2); macAddress = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6; //canPing = true; } else { macAddress = "无法探测到MAC地址"; //canPing = false; } return macAddress; }
|
请发表评论