I have an application made with C# for Android, which searches for all devices connected on my local network by pinging.
With the IPs that exist response, I get the HostName of each device as follows:
private string GetHostName(string ipAddress)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
if (entry != null)
{
return entry.HostName;
}
}
catch (SocketException)
{
return "n/n";
}
return "";
}
I also need to get the MAC address from the IP address. I can't get an example in C# for android (Xamarin)
Is there a way to do it?
UPDATE:
In the first comment to the question, someone has provided a link to a similar thread.
The solution is the next:
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: