Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ping or otherwise tell if a device is on the network by MAC in C#

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.

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?

Edit: 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.

Edit: 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;
}
like image 376
Aric TenEyck Avatar asked Apr 02 '10 14:04

Aric TenEyck


People also ask

Can I find a device on my network by MAC address?

So, if you have a device's MAC address, you can find the related IP address of that device using the protocol called ARP, which contains a table that dynamically maps the MAC address with the IP address of every device in the network.

Can you ping from a Mac?

To do a ping test on Mac, open Finder and go to Applications > Utilities. Then open the Terminal app and type ping followed by a space and then an IP address or domain. To stop the test, hit Control + C on your keyboard.

How do I ping from Mac to Windows?

You can use the ping command to verify the connectivity between two network devices that are IP (Internet Protocol) based. To ping a network device using a system that is running OSX, complete the following: Click Applications > Utilities > Terminal. Type ping -c <number of times to ping> <IP address>.

Does a ping response contain the MAC address of the device?

Does a ping response contain the MAC address of the device or is it possible to ask for it over a local network. Show activity on this post. On a *nix system, you can run arping <some-ip> to get the MAC address of a machine on the same network (only those machines which can get your packet without being routed through a network, of course).

How to use the ping command to test your network?

How to Use the Ping Command to Test Your Network The ping command sends packets of data to a specific IP address on a network, and then lets you know how long it took to transmit that data and get a response. It’s a handy tool that you can use to quickly test various points of your network. Here’s how to use it.

How to Ping An IP address or domain name on Mac?

If you don’t see this option in your left sidebar, you can also hit the Command + A keys on your keyboard from any Finder window. Next, open the Utilities folder. Then open the Terminal app. Next, type ping followed by a space and an IP address or domain name.

How to do a ping test on MacBook Air?

How to Do a Ping Test on a Mac 1 Next, open the Utilities folder. 2 Then open the Terminal app. Next, type ping followed by a space and an IP address or domain name. ... 3 Then hit Enter on your keyboard and wait for the results. 4 Finally, hit Control + C on your keyboard to stop the ping test. ...


1 Answers

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

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

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.

like image 74
spoulson Avatar answered Oct 20 '22 13:10

spoulson