Skip to content

Instantly share code, notes, and snippets.

@ityuhui
Created September 20, 2016 08:05
Show Gist options
  • Save ityuhui/ac141c5c66a3169bc3bd9b078aada647 to your computer and use it in GitHub Desktop.
Save ityuhui/ac141c5c66a3169bc3bd9b078aada647 to your computer and use it in GitHub Desktop.
Windows 根据IP地址获得MAC地址
/*
* For Windows Only
* Find the network interface whose IP address is "ipstr", return the MAC address of this interface in output parameter (macstr),
* and the interface name (ifname)
*
* Input parameters:
* ----ipstr: IP address
* ----ipsize: the buffer size of ipstr
*
* Output parameters:
* ----macstr: MAC address
* ----macsize: the buffer size of macstr
* ----ifname: interface name
* ----ifnsize: the buffer size of ifname
*
* Return value:
* ---- 0 => Get MAC address Succeessfully
* ---- -1 => Fail to get MAC address
*/
static int
getMACByIPWindows(char *macstr, int macsize, char *ifname, int ifnsize, const char *ipstr, int ipsize)
{
static char fname[] = "getMACByIPWindows()";
int rc = -1;
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = NULL;
DWORD dwRetVal = 0;
char buffer[32];
memset(buffer, 0, sizeof(buffer));
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
pAdapterInfo = (IP_ADAPTER_INFO *)HeapAlloc(GetProcessHeap(), 0, (sizeof(IP_ADAPTER_INFO)));
if (pAdapterInfo == NULL) {
ls_syslog(LOG_ERR,"%s: Error allocating memory needed to call GetAdaptersinfo", fname);
return -1;
}
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
HeapFree(GetProcessHeap(), 0, (pAdapterInfo));
pAdapterInfo = (IP_ADAPTER_INFO *)HeapAlloc(GetProcessHeap(), 0, (ulOutBufLen));
if (pAdapterInfo == NULL) {
ls_syslog(LOG_ERR,"%s: Error allocating memory needed to call GetAdaptersinfo", fname);
return -1;
}
}
if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
pAdapter = pAdapterInfo;
while (pAdapter) {
if ( 0 == strncmp(pAdapter->IpAddressList.IpAddress.String, ipstr, ipsize)) {
if ( MAC_ADDRESS_LENGTH == pAdapter->AddressLength) {
sprintf(macstr, "%02x:%02x:%02x:%02x:%02x:%02x",
pAdapter->Address[0],
pAdapter->Address[1],
pAdapter->Address[2],
pAdapter->Address[3],
pAdapter->Address[4],
pAdapter->Address[5]
);
strncpy(ifname, pAdapter->Description, ifnsize-1);
rc = 0; //succeed!
}
}
pAdapter = pAdapter->Next;
}
} else {
ls_syslog(LOG_ERR,"%s: GetAdaptersInfo failed with error: %d", fname, dwRetVal);
return -1;
}
return rc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment