bool IpInSubnet(std::string pcIp1, std::string pcIp2, std::string pcSubNetworkMask)
{
int ip1[4] = { 0 };
int ip2[4] = { 0 };
int ip3[4] = { 0 };
sscanf_s(pcIp1.c_str(), "%d.%d.%d.%d", &ip1[0], &ip1[1], &ip1[2], &ip1[3]);
sscanf_s(pcIp2.c_str(), "%d.%d.%d.%d", &ip2[0], &ip2[1], &ip2[2], &ip2[3]);
sscanf_s(pcSubNetworkMask.c_str(), "%d.%d.%d.%d", &ip3[0], &ip3[1], &ip3[2], &ip3[3]);
for (int i = 0; i < 4; i++)
{
if (ip1[i] < 0 || ip1[i]>255 || ip2[i] < 0 || ip2[i]>255 || ip3[i] < 0 || ip3[i]>255)
{
return FALSE;
}
}
return (ip1[0] & ip3[0]) == (ip2[0] & ip3[0]) && (ip1[1] & ip3[1]) == (ip2[1] & ip3[1]) && (ip1[2] & ip3[2]) == (ip2[2] & ip3[2]) && (ip1[3] & ip3[3]) == (ip2[3] & ip3[3]);
}
bool CheckIpInSubnet(std::string ip, PIP_ADAPTER_INFO cur)
{
IP_ADDR_STRING* pIpAddrString = &(cur->IpAddressList);
IP_ADDR_STRING* pGateway = &(cur->GatewayList);
printf("IP:%s\r\n", pIpAddrString->IpAddress.String);
printf("子网掩码:%s\r\n", pIpAddrString->IpMask.String);
printf("网关:%s\r\n", pGateway->IpAddress.String);
if (IpInSubnet(pIpAddrString->IpAddress.String, ip, pIpAddrString->IpMask.String))
{
return TRUE;
}
return FALSE;
}
std::string GetMacBySubnet(std::string ip)
{
std::string mac = "";
bool found = FALSE;
bool bgetETH0info = FALSE;
PIP_ADAPTER_INFO pIpAdapterInfo = (PIP_ADAPTER_INFO)malloc(sizeof(IP_ADAPTER_INFO) * ADAPTERNUM);// new IP_ADAPTER_INFO[ADAPTERNUM];// 10个网卡空间 足够了
unsigned long stSize = sizeof(IP_ADAPTER_INFO) * ADAPTERNUM;
// 获取所有网卡信息,参数二为输入输出参数
int nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
// 空间不足
if (ERROR_BUFFER_OVERFLOW == nRel) {
// 释放空间
if (pIpAdapterInfo != NULL)
free(pIpAdapterInfo);
return mac;
}
PIP_ADAPTER_INFO cur = pIpAdapterInfo;
// 多个网卡 通过链表形式链接起来的
while (cur) {
printf("网卡描述:%s\r\n", cur->Description);
do {
switch (cur->Type) {
case MIB_IF_TYPE_OTHER:
break;
case MIB_IF_TYPE_ETHERNET:
{
if (CheckIpInSubnet(ip, cur))
{
found = TRUE;
}
break;
}
case MIB_IF_TYPE_TOKENRING:
break;
case MIB_IF_TYPE_FDDI:
break;
case MIB_IF_TYPE_PPP:
break;
case MIB_IF_TYPE_LOOPBACK:
break;
case MIB_IF_TYPE_SLIP:
break;
default://无线网卡,Unknown type
{
if (CheckIpInSubnet(ip, cur))
{
found = TRUE;
}
break;
}
}
} while (false);
char hex[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
// mac 地址一般6个字节
// mac 二进制转16进制字符串
char macStr[18] = { 0 };//12+5+1
int k = 0;
for (int j = 0; j < cur->AddressLength; j++) {
macStr[k++] = hex[(cur->Address[j] & 0xf0) >> 4];
macStr[k++] = hex[cur->Address[j] & 0x0f];
macStr[k++] = '-';
}
macStr[k - 1] = 0;
printf("MAC:%s\r\n", macStr);
if (found&& mac.empty())
{
mac = macStr;
}
cur = cur->Next;
printf("************************************************************************\r\n");
}
// 释放空间
if (pIpAdapterInfo != NULL)
free(pIpAdapterInfo);
return mac;
}
int main()
{
std::string mac = GetMacBySubnet("192.168.1.38");
std::cout << "GetMacBySubnet is :=>" << mac << std::endl;
}
|