GetAdaptersInfo and GetAdaptersAddressess BufferLength Param

前端 未结 3 1127
误落风尘
误落风尘 2021-01-07 07:18

I\'ve got some legacy code in C++ here that does some things I don\'t understand. I\'m running it in Visual C++ 2008 Express Edition on a machine running Windows XP.

<
相关标签:
3条回答
  • 2021-01-07 07:49

    Your code needs to look something like this:

    // First get the desired size.
    unsigned long outBufLen = 0;
    DWORD dwResult = GetAdaptersInfo(NULL, &outBufLen);
    if (dwResult == ERROR_BUFFER_OVERFLOW)  // This is what we're expecting
    {
        // Now allocate a structure of the requried size.
        PIP_ADAPTER_INFO pIpAdapterInfo = (PIP_ADAPTER_INFO) malloc(outBufLen);
        dwResult = GetAdaptersInfo(pIpAdapterInfo, &outBufLen);
        if (dwResult == ERROR_SUCCESS)
        {
            // Yay!
    

    Edit: See also Jeremy Friesner's answer for why this code isn't quite enough.

    0 讨论(0)
  • 2021-01-07 07:54

    Of course, the example code in @RichieHindle's answer contains a race condition.... if the size of the structure Windows wants to return grows after the first call to GetAdaptersInfo() but before the second call to GetAdaptersInfo(), the second call to GetAdaptersInfo() will fail with ERROR_BUFFER_OVERFLOW as well, and your function won't work.

    Yes, that does happen in real life -- I've had it happen to me. If you want the code to be reliable, you need to call GetAdaptersInfo() in a loop, increasing your buffer's size as many times as necessary until the call succeeds.

    There has to be a less error-prone way to construct an API... unfortunately Microsoft hasn't yet found it. :^P

    0 讨论(0)
  • 2021-01-07 08:06

    Indeed, Using Visual studio 6, I used to get the number of adapters by:

    DWORD drc = GetAdaptersInfo(NULL, &(Buflen = 0L));
    
    if (drc == ERROR_BUFFER_OVERFLOW)
      n = Buflen / sizeof(IP_ADAPTER_INFO);
    

    It was all right, for instance for 2 adapters Buflen was set to 1280 and sizeof(IP_ADAPTER_INFO) was 640.

    Now I am using Visual C++ 2008 Express and my result is truncated because the function still sets Buflen to 1280 but the value of sizeof(IP_ADAPTER_INFO) is now 648!

    Is this a bug or am I missing something?

    0 讨论(0)
提交回复
热议问题