我在C#中创建了一个扫描局域网中所有PC的程序,然后打印出IP列表和计算机名称。此处的代码我在YouTube上覆盖了某人。但是当我尝试扫描时,它总是返回错误:
Additional information: An exception occurred during a Ping request.
我尝试在LAN网络中的所有PC中关闭防火墙,但仍然存在此问题。我花了很多时间才弄明白,但仍然不知道下一步该做什么。
Thread myThread = null;
public void scan(string subnet)
{
Ping myPing;
PingReply reply;
IPAddress addr;
IPHostEntry host;
for (int i = 1; i < 255; i++)
{
string subnetn = "." + i.ToString();
myPing = new Ping();
reply = myPing.Send(subnet + subnetn);
if (reply.Status == IPStatus.Success)
{
try
{
addr = IPAddress.Parse(subnet + subnetn);
host = Dns.GetHostEntry(addr);
txtHosts.AppendText(subnet + subnetn + host.HostName.ToString() + "Up");
}
catch
{
}
}
}
}
private void cmdScan_Click(object sender, EventArgs e)
{
myThread = new Thread(() => scan(txtIP.Text));
myThread.Start();
if (myThread.IsAlive)
{
cmdStop.Enabled = true;
cmdScan.Enabled = false;
txtIP.Enabled = false;
}
}
private void cmdStop_Click(object sender, EventArgs e)
{
myThread.Suspend();
cmdScan.Enabled = true;
cmdStop.Enabled = false;
txtIP.Enabled = true;
}
}