Is there a way to get the MAC address of a device on a network based on its IP address? (C# & Android)

DominusDRR

Member
Joined
Nov 19, 2021
Messages
10
Programming Experience
5-10
Hi.

I have an application made for Android in C #.

I'm trying to get the MAC address of a remote device using its IP address as follows:
Get MAC by IP:
  public string GetMacByIP(string ipAddress)
  {
      try
    {
        // grab all online interfaces
        var query = NetworkInterface.GetAllNetworkInterfaces()
            .Where(n =>
                n.OperationalStatus == OperationalStatus.Up && // only grabbing what's online
                n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                .Select(_ => new
                {
                    PhysicalAddress = _.GetPhysicalAddress(),
                    IPProperties = _.GetIPProperties(),
                });

           // grab the first interface that has a unicast address that matches your search string
        var mac = query
                .Where(q => q.IPProperties.UnicastAddresses
                    .Any(ua => ua.Address.ToString() == ipAddress))
                .FirstOrDefault()
                .PhysicalAddress;

            // return the mac address with formatting (eg "00-00-00-00-00-00")
            return String.Join("-", mac.GetAddressBytes().Select(b => b.ToString("X2")));
      }
      catch (Exception ex)
      {
          return ex.Message;
      }
  }
But it only works from the device from where the query is being made, for all the others an exception is thrown in var mac = query .Where(q => q.IPProperties.UnicastAddresses and the error is: 'Object reference not set to an instance of an object

Without try and catch:

1639517011384.png


Any suggestion?
 
FirstOrDefault() will return null if there are no items in the IEnumerable<T>. That means that your Where() is not finding any matches. This makes sense since your source of items is NetworkInterface.GetAllNetworkInterfaces(). That only knows about the network cards on your machine, not about all the network cards in the network.
 

See the last answer regarding examining the ARP cache after sending a broadcast ping.
 
After searching and searching, I have tried many examples, I came to this thread:

Permission Denied for access /proc/net/arp ARP table in Android 10

And write the following code:
C#:
    public static PhysicalAddress Lookup(IPAddress ip)
    {
        var runtime = Java.Lang.Runtime.GetRuntime();
        var proc = runtime.Exec("ip neigh show");
        proc.WaitFor();
        var x = new Java.IO.InputStreamReader(proc.InputStream);
        var reader = new Java.IO.BufferedReader(x);
        String line;
        while ((line = reader.ReadLine()) != null)
        {
            String[] clientInfo = line.Split(" +");
            //if (!clientInfo[3].equalsIgnoreCase("type"))
            //{
            //    String mac = clientInfo[3];
            //    String ip = clientInfo[0];
            //    //textView.append("\n\nip: " + ip + " Mac: " + mac);
            //    //Log.d("IP : ", ip);
            //    //Log.d("Mac : ", mac);
            //}
        }
    }

It is still incomplete, but it is a big step:

1639594975035.png
 

Latest posts

Back
Top Bottom