NetTunnelWindows/NetTunnelSDK/network.cpp

99 lines
3.5 KiB
C++
Raw Normal View History

#include "pch.h"
#include "tunnel.h"
#include "usrerr.h"
#include <strsafe.h>
#include <tchar.h>
#include <Iphlpapi.h>
#include <iostream>
#include "globalcfg.h"
#pragma comment(lib, "Iphlpapi.lib")
int NetmaskToCIDR(const TCHAR *pNetMask) {
const TCHAR *tabCIDR[] = {
TEXT("128.0.0.0"), TEXT("192.0.0.0"), TEXT("224.0.0.0"), TEXT("240.0.0.0"),
TEXT("248.0.0.0"), TEXT("252.0.0.0"), TEXT("254.0.0.0"), TEXT("255.0.0.0"),
TEXT("255.128.0.0"), TEXT("255.192.0.0"), TEXT("255.224.0.0"), TEXT("255.240.0.0"),
TEXT("255.248.0.0"), TEXT("255.252.0.0"), TEXT("255.254.0.0"), TEXT("255.255.0.0"),
TEXT("255.255.128.0"), TEXT("255.255.192.0"), TEXT("255.255.224.0"), TEXT("255.255.240.0"),
TEXT("255.255.248.0"), TEXT("255.255.252.0"), TEXT("255.255.254.0"), TEXT("255.255.255.0"),
TEXT("255.255.255.128"), TEXT("255.255.255.192"), TEXT("255.255.255.224"), TEXT("255.255.255.240"),
TEXT("255.255.255.248"), TEXT("255.255.255.252"), TEXT("255.255.255.254"), TEXT("255.255.255.255")};
for (int i = 0; i < static_cast<int>(std::size(tabCIDR)); i++) {
if (lstrcmp(tabCIDR[i], pNetMask) == 0) {
return i + 1;
}
}
return 0xFF;
}
int GetAllNICInfo(PNIC_CONTENT pInfo, int *pItemCounts) {
int nRel, id = 0;
IP_ADDR_STRING *pIpAddrString;
PIP_ADAPTER_INFO pIpAdapterInfo;
unsigned long stSize;
if (pItemCounts == nullptr || pInfo == nullptr) {
return -ERR_INPUT_PARAMS;
}
pIpAdapterInfo = new IP_ADAPTER_INFO[NET_CARD_MAX];
stSize = sizeof(IP_ADAPTER_INFO) * NET_CARD_MAX;
// WIN32 API get net card information
nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
if (ERROR_BUFFER_OVERFLOW == nRel) {
delete[] pIpAdapterInfo;
return -ERR_MALLOC_MEMORY;
}
PIP_ADAPTER_INFO cur = pIpAdapterInfo;
while (cur) {
StringCbCopy(pInfo[id].NetCardName, MAX_ADAPTER_NAME_LENGTH, cur->AdapterName);
StringCbCopy(pInfo[id].NetCardDescription, MAX_ADAPTER_DESCRIPTION_LENGTH, cur->Description);
switch (cur->Type) {
case MIB_IF_TYPE_ETHERNET:
pIpAddrString = &(cur->IpAddressList);
StringCbCopy(pInfo[id].NetCardIpaddr, 20 - 1, pIpAddrString->IpAddress.String);
StringCbCopy(pInfo[id].NetCardNetmask, 20 - 1, pIpAddrString->IpMask.String);
break;
case MIB_IF_TYPE_OTHER:
case MIB_IF_TYPE_TOKENRING:
case MIB_IF_TYPE_FDDI:
case MIB_IF_TYPE_PPP:
case MIB_IF_TYPE_LOOPBACK:
case MIB_IF_TYPE_SLIP:
break;
default: // WIFI ,Unknown type
pIpAddrString = &(cur->IpAddressList);
StringCbCopy(pInfo[id].NetCardIpaddr, 20 - 1, pIpAddrString->IpAddress.String);
StringCbCopy(pInfo[id].NetCardNetmask, 20 - 1, pIpAddrString->IpMask.String);
break;
}
StringCbPrintf(pInfo[id].NetCardMacAddr,
20 - 1,
"%02X:%02X:%02X:%02X:%02X:%02X",
cur->Address[0],
cur->Address[1],
cur->Address[2],
cur->Address[3],
cur->Address[4],
cur->Address[5]);
id++;
cur = cur->Next;
}
*pItemCounts = id;
delete[] pIpAdapterInfo;
return ERR_SUCCESS;
}