您必须进行 ping 扫描。 System.Net 命名空间中有一个 Ping 类。示例如下。此外,这只有在您的计算机没有运行防火墙的情况下才有可能。如果他们启用了防火墙,那么除了在您的交换机上执行 SNMP 查询之外,无法确定此信息。
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply rep = p.Send("192.168.1.1");
if (rep.Status == System.Net.NetworkInformation.IPStatus.Success)
{
//host is active
}
另一个问题是确定您的网络有多大。在大多数家庭情况下,您的网络掩码将是 24 位。这意味着它设置为 255.255.255.0。如果您的网关是 192.168.1.1,这意味着您网络上的有效地址将是 192.168.1.1 到 192.168.1.254。这是一个IP Calculator 来提供帮助。您必须遍历每个地址并使用 Ping 类 ping 地址并检查 PingReply。
如果您只是寻找信息而不关心如何获取信息,您可以使用 NMap。命令如下
nmap -sP 192.168.1.0/24
编辑:
就速度而言,由于您在本地网络上,因此您可以大大缩短超时间隔,因为您的机器响应时间不应超过 100 毫秒。您还可以使用 SendAsync 并行 ping 它们。以下程序将在半秒内 ping 254 地址。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace ConsoleApplication1
{
class Program
{
static CountdownEvent countdown;
static int upCount = 0;
static object lockObj = new object();
const bool resolveNames = true;
static void Main(string[] args)
{
countdown = new CountdownEvent(1);
Stopwatch sw = new Stopwatch();
sw.Start();
string ipBase = "10.22.4.";
for (int i = 1; i < 255; i++)
{
string ip = ipBase + i.ToString();
Ping p = new Ping();
p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
countdown.AddCount();
p.SendAsync(ip, 100, ip);
}
countdown.Signal();
countdown.Wait();
sw.Stop();
TimeSpan span = new TimeSpan(sw.ElapsedTicks);
Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount);
Console.ReadLine();
}
static void p_PingCompleted(object sender, PingCompletedEventArgs e)
{
string ip = (string)e.UserState;
if (e.Reply != null && e.Reply.Status == IPStatus.Success)
{
if (resolveNames)
{
string name;
try
{
IPHostEntry hostEntry = Dns.GetHostEntry(ip);
name = hostEntry.HostName;
}
catch (SocketException ex)
{
name = "?";
}
Console.WriteLine("{0} ({1}) is up: ({2} ms)", ip, name, e.Reply.RoundtripTime);
}
else
{
Console.WriteLine("{0} is up: ({1} ms)", ip, e.Reply.RoundtripTime);
}
lock(lockObj)
{
upCount++;
}
}
else if (e.Reply == null)
{
Console.WriteLine("Pinging {0} failed. (Null Reply object?)", ip);
}
countdown.Signal();
}
}
}
编辑:在我自己使用了一些之后,我修改了程序以输出有多少 IP 响应的计数。有一个 const 布尔值,如果设置为 true,将导致程序解析 IP 的主机名。但是,这会显着减慢扫描速度。 (不到半秒到16秒)还发现如果IP地址指定错误(自己打错了),回复对象可以为空,所以我处理了。