我正在尝试使用UDP连接在c ++中使用服务器和客户端程序获取另一台计算机的MAC地址。服务器位于一台计算机上(它包含2个列表框,1个用于连接客户端的IP地址,另一个用于MAC地址)客户端位于另一台计算机上。如果我运行服务器和客户端以及同一台计算机,我当前的代码只获取MAC地址。当我调试程序时,我看到当试图获取另一台计算机的MAC地址时程序没有进入if语句并运行PrintMACaddress行(pAdapterInfo->地址);
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;// Contains pointer to current adapter info
bool found = false;
do {
const IP_ADDR_STRING *addr_str = &pAdapterInfo->IpAddressList;
if (addr_str != NULL)
{
if (selected_ip_adr == addr_str->IpAddress.String)
{
PrintMACaddress(pAdapterInfo->Address);
}
}
pAdapterInfo = pAdapterInfo->Next;
}
while(pAdapterInfo);
}
我发现使用ARP功能可能对此有所帮助,或者由于MAC地址是数据,我可能会将其作为字符串或原始数据传输,但我知道如何进行此操作
这是PrintMAC功能:
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);
}
答案 0 :(得分:0)
GetAdaptersInfo
函数仅返回连接到本地计算机的适配器的地址。你应该看看SendARP。
编辑:试试这个:
void CmfcServerDlg::PrintMACFromIP(const CString &selected_ip_adr)
{
DWORD dwRetVal;
IPAddr DestIp = 0;
IPAddr SrcIp = 0; /* default for src ip */
ULONG MacAddr[2]; /* for 6-byte hardware addresses */
ULONG PhysAddrLen = 6; /* default to length of six bytes */
char *SrcIpString = NULL;
BYTE *bPhysAddr;
DestIp = inet_addr(CT2A(selected_ip_adr));
memset(&MacAddr, 0xff, sizeof (MacAddr));
dwRetVal = SendARP(DestIp, SrcIp, &MacAddr, &PhysAddrLen);
if (dwRetVal == NO_ERROR) {
bPhysAddr = (BYTE *) & MacAddr;
if (PhysAddrLen) {
CString theMac;
theMac.Format(_T("%.2X-%.2X-%.2X-%.2X-%.2X-%.2X"), (int) bPhysAddr[0],
(int) bPhysAddr[1],(int) bPhysAddr[2],(int) bPhysAddr[3],(int) bPhysAddr[4],
(int) bPhysAddr[5]);
PrintMACaddress(theMac);
} else
printf
("Warning: SendArp completed successfully, but returned length=0\n");
} else {
printf("Error: SendArp failed with error: %d", dwRetVal);
switch (dwRetVal) {
case ERROR_GEN_FAILURE:
printf(" (ERROR_GEN_FAILURE)\n");
break;
case ERROR_INVALID_PARAMETER:
printf(" (ERROR_INVALID_PARAMETER)\n");
break;
case ERROR_INVALID_USER_BUFFER:
printf(" (ERROR_INVALID_USER_BUFFER)\n");
break;
case ERROR_BAD_NET_NAME:
printf(" (ERROR_GEN_FAILURE)\n");
break;
case ERROR_BUFFER_OVERFLOW:
printf(" (ERROR_BUFFER_OVERFLOW)\n");
break;
case ERROR_NOT_FOUND:
printf(" (ERROR_NOT_FOUND)\n");
break;
default:
printf("\n");
break;
}
}
}
void CmfcServerDlg::PrintMACaddress(CString& strText)
{
m_ClientIdList.AddString(strText);
}