View Single Post
  #2  
Old 07-27-2007, 04:13 AM
kingmaker kingmaker is offline
D-Web Genius
 
Join Date: Jun 2007
Posts: 881
kingmaker is on a distinguished road
Send a message via MSN to kingmaker
Default Re: How to get the MAC Address By IP address in .net?

Hello Oxygen,

We can able to get the MAC address of a system in three ways programmatically.

Method One: UuidCreate
// Fetches the MAC address and prints it
static void GetMACaddress(void)
{
unsigned char MACData[6];

UUID uuid;
UuidCreateSequential( &uuid ); // Ask OS to create UUID

for (int i=2; i<8; i++) // Bytes 2 through 7 inclusive
// are MAC address
MACData[i - 2] = uuid.Data4[i];

PrintMACaddress(MACData); // Print MAC address
}

Method Two: Use NetBIOS
// Fetches the MAC address and prints it
static void GetMACaddress(void)
{
unsigned char MACData[8]; // Allocate data structure
// for MAC (6 bytes needed)

WKSTA_TRANSPORT_INFO_0 *pwkti; // Allocate data structure
// for NetBIOS
DWORD dwEntriesRead;
DWORD dwTotalEntries;
BYTE *pbBuffer;

// Get MAC address via NetBIOS's enumerate function
NET_API_STATUS dwStatus = NetWkstaTransportEnum(
NULL, // [in] server name
0, // [in] data structure to return
&pbBuffer, // [out] pointer to buffer
MAX_PREFERRED_LENGTH, // [in] maximum length
&dwEntriesRead, // [out] counter of elements
// actually enumerated
&dwTotalEntries, // [out] total number of elements
// that could be enumerated
NULL); // [in/out] resume handle
assert(dwStatus == NERR_Success);

pwkti = (WKSTA_TRANSPORT_INFO_0 *)pbBuffer; // type cast the buffer

for(DWORD i=1; i< dwEntriesRead; i++) // first address is
// 00000000, skip it
{ // enumerate MACs & print
swscanf((wchar_t *)pwkti[i].wkti0_transport_address,
L"%2hx%2hx%2hx%2hx%2hx%2hx",
&MACData[0],
&MACData[1],
&MACData[2],
&MACData[3],
&MACData[4],
&MACData[5]);
PrintMACaddress(MACData);
}

// Release pbBuffer allocated by above function
dwStatus = NetApiBufferFree(pbBuffer);
assert(dwStatus == NERR_Success);
}

Method Three: Use GetAdaptersInfo

// Fetches the MAC address and prints it
static void GetMACaddress(void)
{
IP_ADAPTER_INFO AdapterInfo[16]; // Allocate information
// for up to 16 NICs
DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer

DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo
AdapterInfo, // [out] buffer to receive data
&dwBufLen); // [in] size of receive data buffer
assert(dwStatus == ERROR_SUCCESS); // Verify return value is
// valid, no buffer overflow

PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo; // Contains pointer to
// current adapter info
do {
PrintMACaddress(pAdapterInfo->Address); // Print MAC address
pAdapterInfo = pAdapterInfo->Next; // Progress through
// linked list
}
while(pAdapterInfo); // Terminate if last adapter
}

For more Details: CodeGuru: Three ways to get your MAC address.


Hope this is Usefull to you.

The King Maker.
Reply With Quote