Share via


Função GetIfTable (iphlpapi.h)

A função GetIfTable recupera a tabela de interface MIB-II.

Sintaxe

IPHLPAPI_DLL_LINKAGE DWORD GetIfTable(
  [out]     PMIB_IFTABLE pIfTable,
  [in, out] PULONG       pdwSize,
  [in]      BOOL         bOrder
);

Parâmetros

[out] pIfTable

Um ponteiro para um buffer que recebe a tabela de interface como uma estrutura MIB_IFTABLE .

[in, out] pdwSize

Na entrada, especifica o tamanho em bytes do buffer apontado pelo parâmetro pIfTable .

Na saída, se o buffer não for grande o suficiente para manter a tabela de interface retornada, a função definirá esse parâmetro como igual ao tamanho do buffer necessário em bytes.

[in] bOrder

Um valor booliano que especifica se a tabela de interface retornada deve ser classificada em ordem crescente por índice de interface. Se esse parâmetro for TRUE, a tabela será classificada.

Valor retornado

Se a função for bem-sucedida, o valor retornado será NO_ERROR.

Se a função falhar, o valor retornado será um dos códigos de erro a seguir.

Código de retorno Descrição
ERROR_INSUFFICIENT_BUFFER
O buffer apontado pelo parâmetro pIfTable não é grande o suficiente. O tamanho necessário é retornado na variável DWORD apontada pelo parâmetro pdwSize .
ERROR_INVALID_PARAMETER
O parâmetro pdwSize é NULL ou GetIfTable não pode gravar na memória apontada pelo parâmetro pdwSize .
ERROR_NOT_SUPPORTED
Não há suporte para essa função no sistema operacional em uso no sistema local.
Outros
Use a função FormatMessage para obter a cadeia de caracteres de mensagem para o erro retornado.

Comentários

O
A função GetIfTable enumera interfaces físicas em um sistema local e retorna essas informações em uma estrutura MIB_IFTABLE. As interfaces físicas incluem a interface de loopback de software.

As funções GetIfTable2 e GetIfTable2Ex disponíveis no Windows Vista e posteriores são uma versão aprimorada da função GetIfTable que enumera as interfaces físicas e lógicas em um sistema local. As interfaces lógicas incluem várias interfaces wan miniport usadas para L2TP, PPTP, PPOE e outros encapsulamentos de túnel.

As interfaces são retornadas em uma estrutura MIB_IFTABLE no buffer apontado pelo parâmetro pIfTable . A estrutura MIB_IFTABLE contém uma contagem de interfaces e uma matriz de estruturas MIB_IFROW para cada interface.

Observe que a estrutura de MIB_IFTABLE retornada apontada pelo parâmetro pIfTable pode conter preenchimento para alinhamento entre o membro dwNumEntries e a primeira entrada de matriz MIB_IFROW no membro da tabela da estrutura MIB_IFTABLE . O preenchimento para alinhamento também pode estar presente entre as entradas da matriz MIB_IFROW . Qualquer acesso a uma entrada de matriz MIB_IFROW deve assumir que o preenchimento pode existir.

Exemplos

O exemplo a seguir recupera a tabela de interface e imprime o número de entradas na tabela e alguns dados em cada entrada.

#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "IPHLPAPI.lib")

#include <iphlpapi.h>

#include <stdio.h>
#include <stdlib.h>

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

/* Note: could also use malloc() and free() */

int main()
{

    // 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");
        return 1;
    }
    // Make an initial call to GetIfTable to get the
    // necessary size into dwSize
    dwSize = sizeof (MIB_IFTABLE);
    if (GetIfTable(pIfTable, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) {
        FREE(pIfTable);
        pIfTable = (MIB_IFTABLE *) MALLOC(dwSize);
        if (pIfTable == NULL) {
            printf("Error allocating memory needed to call GetIfTable\n");
            return 1;
        }
    }
    // Make a second call to GetIfTable to get the actual
    // data we want.
    if ((dwRetVal = GetIfTable(pIfTable, &dwSize, FALSE)) == NO_ERROR) {
        printf("\tNum Entries: %ld\n\n", pIfTable->dwNumEntries);
        for (i = 0; i < pIfTable->dwNumEntries; i++) {
            pIfRow = (MIB_IFROW *) & pIfTable->table[i];
            printf("\tIndex[%d]:\t %ld\n", i, pIfRow->dwIndex);
            printf("\tInterfaceName[%d]:\t %ws", i, pIfRow->wszName);
            printf("\n");
            printf("\tDescription[%d]:\t ", i);
            for (j = 0; j < pIfRow->dwDescrLen; j++)
                printf("%c", pIfRow->bDescr[j]);
            printf("\n");
            printf("\tType[%d]:\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 %ld\n", i, pIfRow->dwSpeed);
            printf("\tPhysical Addr:\t ");
            if (pIfRow->dwPhysAddrLen == 0)
                printf("\n");
            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("Unreachable\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->dwAdminStatus);
                break;
            }
            printf("\n");
        }
    } else {
        printf("GetIfTable failed with error: \n", dwRetVal);
        if (pIfTable != NULL) {
            FREE(pIfTable);
            pIfTable = NULL;
        }  
        return 1;
        // Here you can use FormatMessage to find out why 
        // it failed.
    }
    if (pIfTable != NULL) {
        FREE(pIfTable);
        pIfTable = NULL;
    }
    return 0;
}


Requisitos

   
Cliente mínimo com suporte Windows 2000 Professional [somente aplicativos da área de trabalho]
Servidor mínimo com suporte Windows 2000 Server [somente aplicativos da área de trabalho]
Plataforma de Destino Windows
Cabeçalho iphlpapi.h
Biblioteca Iphlpapi.lib
DLL Iphlpapi.dll

Confira também

GetIfEntry

GetIfEntry2

GetIfTable2

GetIfTable2Ex

GetNumberOfInterfaces

Referência de função auxiliar de IP

MIB_IFROW

MIB_IFTABLE

MIB_IF_ROW2

MIB_IF_TABLE2