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:
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:
Any suggestion?
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;
}
}
Without try and catch:
Any suggestion?