c++取网络收发字节数
#ifndef UNICODE
#define UNICODE
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "iphlpapi.lib")
void ShowInterfaceInfo();
void Show1();
int Show2();
int Show3();
std::string UnicodeToANSI(const wchar_t* unicode);
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
/* Note: could also use malloc() and free() */
int main()
{
while (1)
{
system("cls");
//Show1();
//Show2();
//ShowInterfaceInfo();
Show3();
Sleep(1000);
}
return 0;
}
void Show1()
{
DWORD dwRetval;
MIB_IPSTATS *pStats;
pStats = (MIB_IPSTATS *)MALLOC(sizeof(MIB_IPSTATS));
if (pStats == NULL) {
wprintf(L"Unable to allocate memory for MIB_IPSTATS\n");
exit(1);
}
dwRetval = GetIpStatistics(pStats);
if (dwRetval != NO_ERROR) {
wprintf(L"GetIpStatistics call failed with %d\n", dwRetval);
exit(1);
}
else {
wprintf(L"IP forwarding: \t\t");
switch (pStats->dwForwarding) {
case MIB_IP_FORWARDING:
wprintf(L"Enabled\n");
break;
case MIB_IP_NOT_FORWARDING:
wprintf(L"Disabled\n");
break;
default:
wprintf(L"unknown value = %d\n", pStats->dwForwarding);
break;
}
wprintf(L"Default initial TTL: \t\t\t\t\t%u\n", pStats->dwDefaultTTL);
wprintf(L"Number of received datagrams: \t\t\t\t%u\n", pStats->dwInReceives);
wprintf(L"Number of received datagrams with header errors: \t%u\n", pStats->dwInHdrErrors);
wprintf(L"Number of received datagrams with address errors: \t%u\n", pStats->dwInAddrErrors);
wprintf(L"Number of datagrams forwarded: \t\t\t\t%ld\n", pStats->dwForwDatagrams);
wprintf(L"Number of received datagrams with an unknown protocol: \t%u\n", pStats->dwInUnknownProtos);
wprintf(L"Number of received datagrams discarded: \t\t%u\n", pStats->dwInDiscards);
wprintf(L"Number of received datagrams delivered: \t\t%u\n", pStats->dwInDelivers);
wprintf(L"Number of outgoing datagrams requested to transmit: \t%u\n", pStats->dwOutRequests);
wprintf(L"Number of outgoing datagrams discarded for routing: \t%u\n", pStats->dwRoutingDiscards);
wprintf(L"Number of outgoing datagrams discarded: \t\t%u\n", pStats->dwOutDiscards);
wprintf(L"Number of outgoing datagrams with no route to destination discarded: %u\n", pStats->dwOutNoRoutes);
wprintf(L"Fragment reassembly timeout: \t\t\t\t%u\n", pStats->dwReasmTimeout);
wprintf(L"Number of datagrams that required reassembly: \t\t%u\n", pStats->dwReasmReqds);
wprintf(L"Number of datagrams successfully reassembled: \t\t%u\n", pStats->dwReasmOks);
wprintf(L"Number of datagrams that could not be reassembled: \t%u\n", pStats->dwReasmFails);
wprintf(L"Number of datagrams fragmented successfully: \t\t%u\n", pStats->dwFragOks);
wprintf(L"Number of datagrams not fragmented and discarded: \t%u\n", pStats->dwFragFails);
wprintf(L"Number of fragments created: \t\t\t\t%u\n", pStats->dwFragCreates);
wprintf(L"Number of interfaces: \t\t\t\t\t%u\n", pStats->dwNumIf);
wprintf(L"Number of IP addresses: \t\t\t\t%u\n", pStats->dwNumAddr);
wprintf(L"Number of routes: \t\t\t\t\t%u\n", pStats->dwNumRoutes);
}
// Free memory allocated for the MIB_IPSTATS structure
if (pStats)
FREE(pStats);
}
int Show2()
{
// Declare and initialize variables.
// Declare and initialize variables.
DWORD dwSize = 0;
DWORD dwRetVal = 0;
unsigned int i, j;
/* variables used for GetIfTable and GetIfEntry */
MIB_IFTABLE *pIfTable;
MIB_IFROW *pIfRow;
// Allocate memory for our pointers.
pIfTable = (MIB_IFTABLE *)MALLOC(sizeof(MIB_IFTABLE));
if (pIfTable == NULL) {
printf("Error allocating memory needed to call GetIfTable\n");
exit(1);
}
// Before calling GetIfEntry, we call GetIfTable to make
// sure there are entries to get and retrieve the interface index.
// Make an initial call to GetIfTable to get the
// necessary size into dwSize
dwSize = sizeof(MIB_IFTABLE);
if (GetIfTable(pIfTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
FREE(pIfTable);
pIfTable = (MIB_IFTABLE *)MALLOC(dwSize);
if (pIfTable == NULL) {
printf("Error allocating memory\n");
exit(1);
}
}
// Make a second call to GetIfTable to get the actual
// data we want.
if ((dwRetVal = GetIfTable(pIfTable, &dwSize, 0)) == NO_ERROR) {
if (pIfTable->dwNumEntries > 0) {
pIfRow = (MIB_IFROW *)MALLOC(sizeof(MIB_IFROW));
if (pIfRow == NULL) {
printf("Error allocating memory\n");
if (pIfTable != NULL) {
FREE(pIfTable);
pIfTable = NULL;
}
exit(1);
}
printf("\tNum Entries: %ld\n\n", pIfTable->dwNumEntries);
for (i = 0; i < pIfTable->dwNumEntries; i++) {
pIfRow->dwIndex = pIfTable->table[i].dwIndex;
if ((dwRetVal = GetIfEntry(pIfRow)) == NO_ERROR) {
printf("\tIndex:\t %ld\n", pIfRow->dwIndex);
printf("\tInterfaceName[%d]:\t ", i);
if (pIfRow->wszName != NULL)
printf("%ws", pIfRow->wszName);
printf("\n");
printf("\tDescription[%d]:\t ", i);
for (j = 0; j < pIfRow->dwDescrLen; j++)
printf("%c", pIfRow->bDescr[j]);
printf("\n");
printf("\tIndex[%d]:\t\t %d\n", i, pIfRow->dwIndex);
printf("\tType[%d]:\t\t ", i);
switch (pIfRow->dwType) {
case IF_TYPE_OTHER:
printf("Other\n");
break;
case IF_TYPE_ETHERNET_CSMACD:
printf("Ethernet\n");
break;
case IF_TYPE_ISO88025_TOKENRING:
printf("Token Ring\n");
break;
case IF_TYPE_PPP:
printf("PPP\n");
break;
case IF_TYPE_SOFTWARE_LOOPBACK:
printf("Software Lookback\n");
break;
case IF_TYPE_ATM:
printf("ATM\n");
break;
case IF_TYPE_IEEE80211:
printf("IEEE 802.11 Wireless\n");
break;
case IF_TYPE_TUNNEL:
printf("Tunnel type encapsulation\n");
break;
case IF_TYPE_IEEE1394:
printf("IEEE 1394 Firewire\n");
break;
default:
printf("Unknown type %ld\n", pIfRow->dwType);
break;
}
printf("\tMtu[%d]:\t\t %ld\n", i, pIfRow->dwMtu);
printf("\tSpeed[%d]:\t\t %ld\n", i, pIfRow->dwSpeed);
printf("\tInOctets[%d]:\t\t %ld\n", i, pIfRow->dwInOctets);
printf("\tOutOctets[%d]:\t\t %ld\n", i, pIfRow->dwOutOctets);
printf("\tPhysical Addr:\t\t ");
if (pIfRow->dwPhysAddrLen == 0)
printf("\n");
// for (j = 0; j < (int) pIfRow->dwPhysAddrLen; j++) {
for (j = 0; j < pIfRow->dwPhysAddrLen; j++) {
if (j == (pIfRow->dwPhysAddrLen - 1))
printf("%.2X\n", (int)pIfRow->bPhysAddr[j]);
else
printf("%.2X-", (int)pIfRow->bPhysAddr[j]);
}
printf("\tAdmin Status[%d]:\t %ld\n", i,
pIfRow->dwAdminStatus);
printf("\tOper Status[%d]:\t ", i);
switch (pIfRow->dwOperStatus) {
case IF_OPER_STATUS_NON_OPERATIONAL:
printf("Non Operational\n");
break;
case IF_OPER_STATUS_UNREACHABLE:
printf("Unreasonable\n");
break;
case IF_OPER_STATUS_DISCONNECTED:
printf("Disconnected\n");
break;
case IF_OPER_STATUS_CONNECTING:
printf("Connecting\n");
break;
case IF_OPER_STATUS_CONNECTED:
printf("Connected\n");
break;
case IF_OPER_STATUS_OPERATIONAL:
printf("Operational\n");
break;
default:
printf("Unknown status %ld\n",
pIfRow->dwOperStatus);
break;
}
printf("\n");
}
else {
printf("GetIfEntry failed for index %d with error: %ld\n",
i, dwRetVal);
// Here you can use FormatMessage to find out why
// it failed.
}
}
}
else {
printf("\tGetIfTable failed with error: %ld\n", dwRetVal);
}
}
return 0;
}
void ShowInterfaceInfo()
{
using namespace std;
DWORD dwNum = 0;
DWORD dwRet = GetNumberOfInterfaces(&dwNum);
if (dwRet != NO_ERROR)
return;
PMIB_IFTABLE pIfTable = NULL;
DWORD dwSize = 0;
dwRet = GetIfTable(pIfTable, &dwSize, TRUE);
if (dwRet == ERROR_INSUFFICIENT_BUFFER)
pIfTable = (PMIB_IFTABLE)malloc(dwSize);
dwRet = GetIfTable(pIfTable, &dwSize, TRUE);
if (dwRet != NO_ERROR)
{
if (pIfTable != NULL)
free(pIfTable);
return;
}
for (int i = 0; i < pIfTable->dwNumEntries; i++)
{
PMIB_IFROW pIfRow = &pIfTable->table[i];
if (pIfRow->dwType != IF_TYPE_ETHERNET_CSMACD && pIfRow->dwType != IF_TYPE_IEEE80211)
continue;
if (pIfRow->dwPhysAddrLen == 0)
continue;
printf("\tIndex:\t %ld\n", pIfRow->dwIndex);
printf("\tInterfaceName[%d]:\t ", i);
if (pIfRow->wszName != NULL)
printf("%ws", pIfRow->wszName);
printf("\n");
printf("\tDescription[%d]:\t ", i);
for (int j = 0; j < pIfRow->dwDescrLen; j++)
printf("%c", pIfRow->bDescr[j]);
printf("\n");
printf("\tIndex[%d]:\t\t %d\n", i, pIfRow->dwIndex);
printf("\tType[%d]:\t\t ", i);
switch (pIfRow->dwType) {
case IF_TYPE_OTHER:
printf("Other\n");
break;
case IF_TYPE_ETHERNET_CSMACD:
printf("Ethernet\n");
break;
case IF_TYPE_ISO88025_TOKENRING:
printf("Token Ring\n");
break;
case IF_TYPE_PPP:
printf("PPP\n");
break;
case IF_TYPE_SOFTWARE_LOOPBACK:
printf("Software Lookback\n");
break;
case IF_TYPE_ATM:
printf("ATM\n");
break;
case IF_TYPE_IEEE80211:
printf("IEEE 802.11 Wireless\n");
break;
case IF_TYPE_TUNNEL:
printf("Tunnel type encapsulation\n");
break;
case IF_TYPE_IEEE1394:
printf("IEEE 1394 Firewire\n");
break;
default:
printf("Unknown type %ld\n", pIfRow->dwType);
break;
}
printf("\tMtu[%d]:\t\t %ld\n", i, pIfRow->dwMtu);
printf("\tSpeed[%d]:\t\t %ld\n", i, pIfRow->dwSpeed);
printf("\tInOctets[%d]:\t\t %ld\n", i, pIfRow->dwInOctets);
printf("\tOutOctets[%d]:\t\t %ld\n", i, pIfRow->dwOutOctets);
printf("\tPhysical Addr:\t\t ");
if (pIfRow->dwPhysAddrLen == 0)
printf("\n");
// for (j = 0; j < (int) pIfRow->dwPhysAddrLen; j++) {
for (int j = 0; j < pIfRow->dwPhysAddrLen; j++) {
if (j == (pIfRow->dwPhysAddrLen - 1))
printf("%.2X\n", (int)pIfRow->bPhysAddr[j]);
else
printf("%.2X-", (int)pIfRow->bPhysAddr[j]);
}
printf("\tAdmin Status[%d]:\t %ld\n", i,
pIfRow->dwAdminStatus);
printf("\tOper Status[%d]:\t ", i);
switch (pIfRow->dwOperStatus) {
case IF_OPER_STATUS_NON_OPERATIONAL:
printf("Non Operational\n");
break;
case IF_OPER_STATUS_UNREACHABLE:
printf("Unreasonable\n");
break;
case IF_OPER_STATUS_DISCONNECTED:
printf("Disconnected\n");
break;
case IF_OPER_STATUS_CONNECTING:
printf("Connecting\n");
break;
case IF_OPER_STATUS_CONNECTED:
printf("Connected\n");
break;
case IF_OPER_STATUS_OPERATIONAL:
printf("Operational\n");
break;
default:
printf("Unknown status %ld\n",
pIfRow->dwOperStatus);
break;
}
printf("\n");
}
if (pIfTable != NULL)
free(pIfTable);
}
#define WORKING_BUFFER_SIZE 15000
#define MAX_TRIES 3
int Show3()
{
/* Declare and initialize variables */
DWORD dwSize = 0;
DWORD dwRetVal = 0;
unsigned int i = 0;
// Set the flags to pass to GetAdaptersAddresses
ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
// default to unspecified address family (both)
ULONG family = AF_UNSPEC;
LPVOID lpMsgBuf = NULL;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
ULONG outBufLen = 0;
ULONG Iterations = 0;
PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
PIP_ADAPTER_ANYCAST_ADDRESS pAnycast = NULL;
PIP_ADAPTER_MULTICAST_ADDRESS pMulticast = NULL;
IP_ADAPTER_DNS_SERVER_ADDRESS *pDnServer = NULL;
IP_ADAPTER_PREFIX *pPrefix = NULL;
//if (argc != 2) {
// printf(" Usage: getadapteraddresses family\n");
// printf(" getadapteraddresses 4 (for IPv4)\n");
// printf(" getadapteraddresses 6 (for IPv6)\n");
// printf(" getadapteraddresses A (for both IPv4 and IPv6)\n");
// exit(1);
//}
//if (atoi(argv[1]) == 4)
// family = AF_INET;
//else if (atoi(argv[1]) == 6)
// family = AF_INET6;
printf("Calling GetAdaptersAddresses function with family = ");
if (family == AF_INET)
printf("AF_INET\n");
if (family == AF_INET6)
printf("AF_INET6\n");
if (family == AF_UNSPEC)
printf("AF_UNSPEC\n\n");
MIB_IFROW *pIfRow = (MIB_IFROW *)MALLOC(sizeof(MIB_IFROW));
// Allocate a 15 KB buffer to start with.
outBufLen = WORKING_BUFFER_SIZE;
do {
pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
if (pAddresses == NULL) {
printf
("Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n");
exit(1);
}
dwRetVal =
GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
FREE(pAddresses);
pAddresses = NULL;
}
else {
break;
}
Iterations++;
} while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));
if (dwRetVal == NO_ERROR) {
// If successful, output some information from the data we received
pCurrAddresses = pAddresses;
while (pCurrAddresses) {
pIfRow->dwIndex = pCurrAddresses->IfIndex;
if ((dwRetVal = GetIfEntry(pIfRow)) == NO_ERROR) {
;
}
else
{
// 拿不到信息
pCurrAddresses = pCurrAddresses->Next;
continue;
}
if (!pCurrAddresses->FriendlyName)
{
// 没有显示名
pCurrAddresses = pCurrAddresses->Next;
continue;
}
if (0 == pCurrAddresses->PhysicalAddressLength)
{
// 没有mac
pCurrAddresses = pCurrAddresses->Next;
continue;
}
std::string name = UnicodeToANSI(pCurrAddresses->FriendlyName);
printf("\tFriendly name: %s\n", name.c_str());
printf("\tLength of the IP_ADAPTER_ADDRESS struct: %ld\n",
pCurrAddresses->Length);
printf("\tIfIndex (IPv4 interface): %u\n", pCurrAddresses->IfIndex);
printf("\tAdapter name: %s\n", pCurrAddresses->AdapterName);
// 接收
printf("\tInOctets[%d]:\t\t %ld\n", pCurrAddresses->IfIndex, pIfRow->dwInOctets);
// 发送
printf("\tOutOctets[%d]:\t\t %ld\n", pCurrAddresses->IfIndex, pIfRow->dwOutOctets);
pUnicast = pCurrAddresses->FirstUnicastAddress;
if (pUnicast != NULL) {
for (i = 0; pUnicast != NULL; i++)
pUnicast = pUnicast->Next;
printf("\tNumber of Unicast Addresses: %d\n", i);
}
else
printf("\tNo Unicast Addresses\n");
pAnycast = pCurrAddresses->FirstAnycastAddress;
if (pAnycast) {
for (i = 0; pAnycast != NULL; i++)
pAnycast = pAnycast->Next;
printf("\tNumber of Anycast Addresses: %d\n", i);
}
else
printf("\tNo Anycast Addresses\n");
pMulticast = pCurrAddresses->FirstMulticastAddress;
if (pMulticast) {
for (i = 0; pMulticast != NULL; i++)
pMulticast = pMulticast->Next;
printf("\tNumber of Multicast Addresses: %d\n", i);
}
else
printf("\tNo Multicast Addresses\n");
pDnServer = pCurrAddresses->FirstDnsServerAddress;
if (pDnServer) {
for (i = 0; pDnServer != NULL; i++)
pDnServer = pDnServer->Next;
printf("\tNumber of DNS Server Addresses: %d\n", i);
}
else
printf("\tNo DNS Server Addresses\n");
printf("\tDNS Suffix: %wS\n", pCurrAddresses->DnsSuffix);
printf("\tDescription: %wS\n", pCurrAddresses->Description);
//printf("\tFriendly name: %wS\n", pCurrAddresses->FriendlyName);
if (pCurrAddresses->PhysicalAddressLength != 0) {
printf("\tPhysical address: ");
for (i = 0; i < (int)pCurrAddresses->PhysicalAddressLength;
i++) {
if (i == (pCurrAddresses->PhysicalAddressLength - 1))
printf("%.2X\n",
(int)pCurrAddresses->PhysicalAddress[i]);
else
printf("%.2X-",
(int)pCurrAddresses->PhysicalAddress[i]);
}
}
printf("\tFlags: %ld\n", pCurrAddresses->Flags);
printf("\tMtu: %lu\n", pCurrAddresses->Mtu);
printf("\tIfType: %ld\n", pCurrAddresses->IfType);
printf("\tOperStatus: %ld\n", pCurrAddresses->OperStatus);
printf("\tIpv6IfIndex (IPv6 interface): %u\n",
pCurrAddresses->Ipv6IfIndex);
printf("\tZoneIndices (hex): ");
for (i = 0; i < 16; i++)
printf("%lx ", pCurrAddresses->ZoneIndices[i]);
printf("\n");
printf("\tTransmit link speed: %I64u\n", pCurrAddresses->TransmitLinkSpeed);
printf("\tReceive link speed: %I64u\n", pCurrAddresses->ReceiveLinkSpeed);
pPrefix = pCurrAddresses->FirstPrefix;
if (pPrefix) {
for (i = 0; pPrefix != NULL; i++)
pPrefix = pPrefix->Next;
printf("\tNumber of IP Adapter Prefix entries: %d\n", i);
}
else
printf("\tNumber of IP Adapter Prefix entries: 0\n");
printf("\n");
pCurrAddresses = pCurrAddresses->Next;
}
}
else {
printf("Call to GetAdaptersAddresses failed with error: %d\n",
dwRetVal);
if (dwRetVal == ERROR_NO_DATA)
printf("\tNo addresses were found for the requested parameters\n");
else {
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
(LPTSTR)& lpMsgBuf, 0, NULL)) {
printf("\tError: %s", lpMsgBuf);
LocalFree(lpMsgBuf);
if (pAddresses)
FREE(pAddresses);
exit(1);
}
}
}
if (pAddresses) {
FREE(pAddresses);
}
if (pIfRow)
FREE(pIfRow);
return 0;
}
std::string UnicodeToANSI(const wchar_t* unicode)
{
#ifdef WIN32
int textlen = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, NULL);
char* pBuffer = new char[textlen + 1];
memset(pBuffer, 0, sizeof(char) * (textlen + 1));
WideCharToMultiByte(CP_ACP, 0, unicode, -1, pBuffer, textlen, NULL, NULL);
std::string ansi{ pBuffer };
delete[] pBuffer;
return ansi;
#else
QString string = "...";
QTextCodec *codec = QTextCodec::codecForName("GBK");
QByteArray encodedString = codec->fromUnicode(string);
return nullptr;
#endif
}
参考:
https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getifentry
https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getiftable