-1

我有这个:

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Iphlpapi.h>
#include <Assert.h>
#include <sstream>

#pragma comment(lib, "iphlpapi.lib")

using namespace std;

// Prints the MAC address stored in a 6 byte array to stdout
static void PrintMACaddress(unsigned char MACData[])
{

    printf("%02X-%02X-%02X-%02X-%02X-%02X", 
        MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

}

// Fetches the MAC address and prints it
static void GetMACaddress(void)
{
    IP_ADAPTER_INFO AdapterInfo[16];            // Allocate information for up to 16 NICs
    DWORD dwBufLen = sizeof(AdapterInfo);       // Save the memory size of buffer

    DWORD dwStatus = GetAdaptersInfo(           // Call GetAdapterInfo
        AdapterInfo,                            // [out] buffer to receive data
        &dwBufLen);                             // [in] size of receive data buffer
    assert(dwStatus == ERROR_SUCCESS);          // Verify return value is valid, no buffer overflow

    PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;// Contains pointer to current adapter info
    do {
        PrintMACaddress(pAdapterInfo->Address); // Print MAC address
        pAdapterInfo = pAdapterInfo->Next;      // Progress through linked list
    }
    while(pAdapterInfo);                        // Terminate if last adapter
}

    int _tmain(int argc, _TCHAR* argv[])
    {
    char mac[100];

        GetMACaddress(); // output is 00-19-D7-53-2D-14

    std::stringstream buffer;
    buffer << "Text" << std::endl;
    cout << buffer.str();
        return 0;
    }

我的问题是如何将函数GetMACaddress();输出分配给变量。这:mac = GetMACaddress(); // output is 00-19-D7-53-2D-14不工作。请帮帮我。谢谢你。

返回 MAC 地址的数据类型为unsigned char

4

3 回答 3

0

您需要将stdout缓冲区重定向到字符串流,如下所示:

stringstream ss;
streambuf* old = std::cout.rdbuf(ss.rdbuf()); // redirect stdout, and also save the old one

GetMACAddress();

string theStr = ss.str();
cout << theStr << endl;

// when you are done, redirect back to the "real" stdout
cout.rdbuf(old);
于 2012-12-03T17:10:32.120 回答
0

您的函数PrintMACaddress打印 MAC 地址;您需要一个类似的函数来接收unsigned char MACData[]但返回 MAC 地址而不是打印它。

// Converts the MAC address stored in a 6 byte array to a string
std::string ConvertMACaddressToString(unsigned char MACData[])
{
    ...
}

要实现它,首先替换printfsprintf

char result[18]; // 18 bytes are just enough to hold the MAC address
sprintf(result, "%02X-%02X-%02X-%02X-%02X-%02X", 
    MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

然后从函数返回值:

return result;
于 2012-12-03T18:15:01.750 回答
0

如果返回mac地址的数据类型是unsigned char,可以存储在里面。

unsigned char output = GetMACaddress() ;

如果它是一串字符,则用于std::string存储返回的 mac 地址,如果您说的是 pattern 的输出00-19-D7-53-2D-14

std::string output = GetMACaddress() ;

如果是其他类型,您可以让编译器在运行时决定。如果您使用的是 C++11,则可以使用autodecltype.

auto return_val = GetMACaddress() ;
于 2012-12-03T17:06:39.053 回答