Retreiving the correct MacAddress using the corresponding IP address

D

DaTurk

Hi,

I want to to find the Mac address of the NIC being used by a given
process using a corresponding IP address. It should be pointed out
that the machines that this program will be running on will be using
more then one NIC. SO I have to use the IP adress to get the correct
MAC. Here is the code I'm using to get the IP. Any help would be
greatly appreciated, and thank you in advance.

public static IPAddress GetLocalIP()
{
IPAddress localIp = null;
String hostName = Dns.GetHostName();
IPHostEntry ipHostEntry = Dns.GetHostByName(hostName);

if( ipHostEntry.AddressList.Length >= 1 )
{
localIp = ipHostEntry.AddressList[0];
}
return localIp;
}

I know I'm just grabbing the first one, but for the purposes of the
program it doesn't really matter. But it does matter that the Mac
Address I grab correspond to this IP I'm grabbing here. Thanks again
 
D

DaTurk

NeverMind, I figured it out. In case anyone is having the same
problem, this is the solution I came up with.

public static String GetPhysicalAddress(String ipAddress)
{
String[] ipAddresses = null;
String macAddress = null;
ManagementObjectSearcher query = null;
ManagementObjectCollection queryCollection = null;

try
{
query = new ManagementObjectSearcher("SELECT * FROM
Win32_NetworkAdapterConfiguration") ;
queryCollection = query.Get();

foreach(ManagementObject mo in queryCollection)
{
Console.WriteLine(queryCollection.Count);
if(mo["IpAddress"] != null)
{
ipAddresses = (String[])mo["IPAddress"];

foreach(String ip in ipAddresses)
{
if(ip.CompareTo(ipAddress) == 0)
{
if(mo["MacAddress"] != null)
{
macAddress = (String)mo["MacAddress"];
break;
}
}
}
}
}
}
catch(Exception ex)
{
}
return macAddress;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top