线程ARP ping

时间:2014-03-07 09:16:34

标签: c# ping arp

我正在开发C#代码,用于ping一个子网内的所有主机(1-255)和ARP请求(有趣的是有多少设备响应ARP请求,但没有ping通)。

使用Ping我可以设置超时并运行Async,扫描子网需要一秒钟。我不确定如何使用ARP,因为我无法设置超时值。我可以在线程中发送请求吗?我对多线程的经验不多,但欢迎任何帮助。

[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint, PhyAddrLen);

...

if (SendARP(intAddress, 0, macAddr, ref macAddrLen) == 0)
{
// Host found! Woohoo
}

1 个答案:

答案 0 :(得分:2)

这应该这样做。当然,可能没有订购控制台输出。

class Program
{
    [DllImport("iphlpapi.dll", ExactSpelling = true)]
    public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);

    static void Main(string[] args)
    {
        List<IPAddress> ipAddressList = new List<IPAddress>();

        //Generating 192.168.0.1/24 IP Range
        for (int i = 1; i < 255; i++)
        {
            //Obviously you'll want to safely parse user input to catch exceptions.
            ipAddressList.Add(IPAddress.Parse("192.168.0." + i));
        }

        foreach (IPAddress ip in ipAddressList)
        {
            Thread thread = new Thread(() => SendArpRequest(ip));
            thread.Start();

        }
    }

    static void SendArpRequest(IPAddress dst)
    {
        byte[] macAddr = new byte[6];
        uint macAddrLen = (uint)macAddr.Length;
        int uintAddress = BitConverter.ToInt32(dst.GetAddressBytes(), 0);

        if (SendARP(uintAddress, 0, macAddr, ref macAddrLen) == 0)
        {
            Console.WriteLine("{0} responded to ping", dst.ToString());
        }
    }
}