Ping或以其他方式通过C#中的MAC判断设备是否在网络上 [英] Ping or otherwise tell if a device is on the network by MAC in C#

查看:288
本文介绍了Ping或以其他方式通过C#中的MAC判断设备是否在网络上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发家庭安全应用程序.我想做的一件事是根据我是否在家自动关闭和打开它.我有一个带有Wifi的电话,当我在家时,该电话会自动连接到我的网络.

I'm developing a home security application. One thing I'd like to do is automatically turn it off and on based on whether or not I'm at home. I have a phone with Wifi that automatically connects to my network when I'm home.

电话将通过DHCP连接并获取其地址.虽然我可以将其配置为使用静态IP,但我不希望这样做.在C#/.Net中是否存在任何类型的"Ping"或同等功能,它们可以获取设备的MAC地址并告诉我该设备当前是否在网络上处于活动状态?

The phone connects and gets its address via DHCP. While I could configure it to use a static IP, I'd rather not. Is there any kind of 'Ping' or equivalent in C# / .Net that can take the MAC address of a device and tell me whether or not it's currently active on the network?

为了澄清,我正在PC上运行我希望能够在同一LAN上检测到电话的软件.

To clarify, I'm running software on a PC that I'd like to have be able to detect the phone on the same LAN.

这是我想出的代码,这要感谢Spoulson的帮助.它可以可靠地检测出我感兴趣的任何电话是否在家里.

Here is the code that I came up with, thanks to spoulson's help. It reliably detects whether or not any of the phones I'm interested in are in the house.

private bool PhonesInHouse()
{

    Ping p = new Ping();
    // My home network is 10.0.23.x, and the DHCP 
    // pool runs from 10.0.23.2 through 10.0.23.127.

    int baseaddr = 10;
    baseaddr <<= 8;
    baseaddr += 0;
    baseaddr <<= 8;
    baseaddr += 23;
    baseaddr <<= 8;

    // baseaddr is now the equivalent of 10.0.23.0 as an int.

    for(int i = 2; i<128; i++) {
        // ping every address in the DHCP pool, in a separate thread so 
        // that we can do them all at once
        IPAddress ip = new IPAddress(IPAddress.HostToNetworkOrder(baseaddr + i));
        Thread t = new Thread(() => 
             { try { Ping p = new Ping(); p.Send(ip, 1000); } catch { } });
        t.Start();
    }

    // Give all of the ping threads time to exit

    Thread.Sleep(1000);

    // We're going to parse the output of arp.exe to find out 
    // if any of the MACs we're interested in are online

    ProcessStartInfo psi = new ProcessStartInfo();
    psi.Arguments = "-a";
    psi.FileName = "arp.exe";
    psi.RedirectStandardOutput = true;
    psi.UseShellExecute = false;
    psi.CreateNoWindow = true;

    bool foundone = false;
    using (Process pro = Process.Start(psi))
    {
        using (StreamReader sr = pro.StandardOutput)
        {
            string s = sr.ReadLine();

            while (s != null)
            {
                if (s.Contains("Interface") || 
                    s.Trim() == "" || 
                    s.Contains("Address"))
                {
                    s = sr.ReadLine();
                    continue;
                }
                string[] parts = s.Split(new char[] { ' ' }, 
                    StringSplitOptions.RemoveEmptyEntries);

                // config.Phones is an array of strings, each with a MAC 
                // address in it.
                // It's up to you to format them in the same format as 
                // arp.exe
                foreach (string mac in config.Phones)
                {
                    if (mac.ToLower().Trim() == parts[1].Trim().ToLower())
                    {
                        try
                        {
                            Ping ping = new Ping();
                            PingReply pingrep = ping.Send(parts[0].Trim());
                            if (pingrep.Status == IPStatus.Success)
                            {
                                foundone = true;
                            }
                        }
                        catch { }
                        break;
                    }
                }
                s = sr.ReadLine();
            }
        }
    }

    return foundone;
}

推荐答案

另一种方法是使用pingarp工具.由于ARP数据包只能保留在同一广播域中,因此您可以ping您网络的广播地址,并且每个客户端都将以ARP响应进行回复.这些响应中的每一个都缓存在您的ARP表中,您可以使用命令arp -a查看该表.因此,摘要:

A different approach is to use ping and arp tools. Since ARP packets can only stay in the same broadcast domain, you could ping your network's broadcast address and every client will reply with an ARP response. Each of those responses are cached in your ARP table, which you can view with the command arp -a. So the rundown:

rem Clear ARP cache
netsh interface ip delete arpcache

rem Ping broadcast addr for network 192.168.1.0
ping -n 1 192.168.1.255

rem View ARP cache to see if the MAC addr is listed
arp -a

其中一些可以在托管代码中完成,例如在 System.Net.NetworkInformation 命名空间.

Some of these can be done in managed code, such as in the System.Net.NetworkInformation namespace.

注意:清除ARP缓存可能会通过清除其他本地服务器的缓存条目而对网络性能产生轻微影响.但是,无论如何通常通常每20分钟或更短时间清除一次缓存.

Note: Clearing the ARP cache may have a marginal affect on network performance by clearing cached entries of other local servers. However, the cache is usually cleared every 20 minutes or less anyway.

这篇关于Ping或以其他方式通过C#中的MAC判断设备是否在网络上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆