问题
i have a client server application in MFC using UDP where the server displays the IP address of connected clients in a listbox. If i run the client and server on the same computer the program displays the MAC address but if i try to run the client on a different computer the program crashes. Here are the 3 functions. I have an event handler for the listbox that displays the MAC address in a second listbox when an IP address is selected. PrintMACFromIP is the code for getting the MAC address
void CmfcServerDlg::OnLbnSelchangeListClientaddr()
{
BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
int nIndex = m_ClientAddrList.GetCurSel();
if(nIndex < 0)
return;
CString s1;
m_ClientAddrList.GetText(nIndex, s1);
PrintMACFromIP(s1);
}
void CmfcServerDlg::PrintMACaddress(unsigned char MACData[])
{
CString strText;
strText.Format("%02X-%02X-%02X-%02X-%02X-%02X\n",MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);
m_ClientIdList.AddString(strText);
}
void CmfcServerDlg:: PrintMACFromIP(const CString &selected_ip_adr)
{
IP_ADAPTER_INFO AdapterInfo[16];
DWORD dwBufLen = sizeof(AdapterInfo);
DWORD dwStatus = GetAdaptersInfo(
AdapterInfo,
&dwBufLen);
assert(dwStatus == ERROR_SUCCESS);
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
bool found = false;
do {
const IP_ADDR_STRING *addr_str = &pAdapterInfo->IpAddressList;
while(addr_str != NULL)
{
if(selected_ip_adr == addr_str->IpAddress.String)
{
found = true;
break;
}
}
if(found)
{
PrintMACaddress(pAdapterInfo->Address);
break;
}
else
{
pAdapterInfo = pAdapterInfo->Next;
}
}
while(pAdapterInfo);
}
回答1:
I believe your bug is here :
while(addr_str != NULL)
{
if(selected_ip_adr == addr_str->IpAddress.String)
{
found = true;
break;
}
}
Change the while
to if (addr_str != NULL)
then
it should look like
if (add_str != NULL)
{
if (selected_ip_adr == addr_str->IpAddress.String)
{
PrintMACaddress(pAdapterInfo->Address);
}
}
pAdapterInfo = pAdapterInfo->Next;
This should handle if pAdapterInfo is null by using the do/while on the subsequent next
calls.
See IP_ADAPTER_INFO structure at MSDN.
来源:https://stackoverflow.com/questions/15636581/program-crashes-when-i-try-find-mac-address