使用ARP Ping总是使主机离线

本文关键字:主机 离线 ARP Ping 使用 | 更新日期: 2023-09-27 18:21:11

我试图通过使用代码来检查网络上的计算机是否在线,该代码应该通过使用ARP数据包来检查它。

我总是收到主机离线的消息,即使我确信它是在线的。我已经检查了我的本地主机IP和一些始终可用的IP,如谷歌。

这个代码可能有问题?

[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(IPAddress DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
private byte[] macAddr = new byte[6];
private uint macAddrLen;
private void Ping(IPAddress address)
{
    if (SendARP(address, 0, new byte[6], ref macAddrLen) == 0)
    {
        open++;
        txtDisplay.AppendText("Host " + address + " is open." + Environment.NewLine);
    }
    else
    {
        closed++;
        txtDisplay.AppendText("Host " + address + " is closed." + Environment.NewLine);
    }
}

通过使用以前的代码,我基本上是在尝试做一些类似下面代码的事情。但这个代码的问题是,当主机关闭时,大约需要2秒钟才能得到我想要消除的响应。有人建议使用ARP ping:

private void Ping(IPAddress address)
{
    Ping pingSender = new Ping();
    PingOptions options = new PingOptions();
    if (cbDontFragment.Checked) options.DontFragment = true;
    else options.DontFragment = false;
    string dataa = string.Empty;
    int dataCounter = 0;
    options.Ttl = (int)nudTTL.Value;
    for (int i = 0; i < nudData.Value; i++)
    {
        dataCounter++;
        if (dataCounter == 10) dataCounter = 0;
        dataa += dataCounter.ToString();
    }
    byte[] buffer = Encoding.ASCII.GetBytes(dataa);
    int timeout = 120;
    try
    {
        PingReply reply = pingSender.Send(address, timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            open++;
            txtDisplay.AppendText("Host " + address + " is open. ");
            if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
            txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
            txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
            txtDisplay.AppendText(Environment.NewLine);
        }
        else
        {
            closed++;
            txtDisplay.AppendText("Host " + address + " is closed. ");
            if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
            txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
            txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
            txtDisplay.AppendText(Environment.NewLine);
        }
    }
    catch (Exception ex)
    {
        txtDisplay.SelectedText += Environment.NewLine + ex.Message;
    }
}

使用ARP Ping总是使主机离线

ARP不能用于您要做的事情。它只能在本地网络上工作。

它的目的是将IP地址(已路由)解析为MAC地址(未路由)。它永远不会发送到网段(局域网)之外。