Share via


Função LookupPersistentTcpPortReservation (iphlpapi.h)

A função LookupPersistentTcpPortReservation procura o token para uma reserva de porta TCP persistente para um bloco consecutivo de portas TCP no computador local.

Sintaxe

IPHLPAPI_DLL_LINKAGE ULONG LookupPersistentTcpPortReservation(
  [in]  USHORT   StartPort,
  [in]  USHORT   NumberOfPorts,
  [out] PULONG64 Token
);

Parâmetros

[in] StartPort

O número da porta TCP inicial na ordem de bytes de rede.

[in] NumberOfPorts

O número de números de porta TCP que foram reservados.

[out] Token

Um ponteiro para um token de reserva de porta retornado se a função for bem-sucedida.

Retornar valor

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

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

Código de retorno Descrição
ERROR_INVALID_PARAMETER
Um parâmetro inválido foi passado para a função. Esse erro será retornado se zero for passado nos parâmetros StartPort ou NumberOfPorts .
ERROR_NOT_FOUND
O elemento não foi encontrado. Esse erro será retornado se o bloco de porta persistente especificado pelos parâmetros StartPort e NumberOfPorts não puder ser encontrado.
Outros
Use FormatMessage para obter a cadeia de caracteres de mensagem para o erro retornado.

Comentários

A função LookupPersistentTcpPortReservation é definida no Windows Vista e posterior.

A função LookupPersistentTcpPortReservation é usada para pesquisar o token para uma reserva persistente para um bloco de portas TCP.

Uma reserva persistente para um bloco de portas TCP é criada por uma chamada para a função CreatePersistentTcpPortReservation . Os parâmetros StartPort ou NumberOfPorts passados para a função LookupPersistentTcpPortReservation devem corresponder aos valores usados quando a reserva persistente para um bloco de portas TCP foi criada pela função CreatePersistentTcpPortReservation .

Se a função LookupPersistentTcpPortReservation for bem-sucedida, o parâmetro Token retornado apontará para o token para a reserva de porta persistente para o bloco de portas TCP. Observe que o token de uma determinada reserva persistente para um bloco de portas TCP pode ser alterado sempre que o sistema é reiniciado.

Um aplicativo pode solicitar atribuições de porta da reserva de porta TCP abrindo um soquete TCP e chamando a função WSAIoctl especificando a SIO_ASSOCIATE_PORT_RESERVATION IOCTL e passando o token de reserva antes de emitir uma chamada para a função de associação no soquete.

Exemplos

O exemplo a seguir pesquisa uma reserva de porta TCP persistente e, em seguida, cria um soquete e aloca uma porta da reserva de porta.

#ifndef UNICODE
#define UNICODE
#endif

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <Windows.h.>
#include <winsock2.h>
#include <mstcpip.h>
#include <ws2ipdef.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>

// Need to link with iphlpapi.lib
#pragma comment(lib, "iphlpapi.lib")

// Need to link with Ws2_32.lib for Winsock functions
#pragma comment(lib, "ws2_32.lib")

int wmain(int argc, WCHAR **argv)  {

    // Declare and initialize variables
    
    int startPort = 0;         // host byte order
    int numPorts = 0;
    USHORT startPortns = 0;    // Network byte order
    ULONG64 resToken = {0};
    
    unsigned long status = 0;

    WSADATA wsaData = { 0 };
    int iResult = 0;

    SOCKET sock = INVALID_SOCKET;
    int iFamily = AF_INET;
    int iType = SOCK_STREAM;
    int iProtocol = IPPROTO_TCP;

    DWORD bytesReturned = 0;

    // Note that the sockaddr_in struct works only with AF_INET not AF_INET6
    // An application needs to use the sockaddr_in6 for AF_INET6
    sockaddr_in service; 
    sockaddr_in sockName;
    int nameLen = sizeof(sockName);
    
    // Validate the parameters
    if (argc != 3) {
        wprintf(L"usage: %s <Starting Port> <Number of Ports>\n", 
            argv[0]);
        wprintf(L"Look up a persistent TCP port reservation\n");
        wprintf(L"Example usage:\n");
        wprintf(L"   %s 5000 20\n", argv[0]);
        wprintf(L"   where StartPort=5000 NumPorts=20");
        return 1;
    }

    startPort = _wtoi(argv[1]);
    if ( startPort < 0 || startPort> 65535) {
        wprintf(L"Starting point must be either 0 or between 1 and 65,535\n");
        return 1;
    }    
    startPortns = htons((USHORT) startPort);

    numPorts = _wtoi(argv[2]);
    if (numPorts < 0) {
        wprintf(L"Number of ports must be a positive number\n");
        return 1;
    }    

    status = LookupPersistentTcpPortReservation((USHORT) startPortns, (USHORT) numPorts, &resToken);
    if( status != NO_ERROR )
    {
        wprintf(L"LookupPersistentTcpPortReservation returned error: %ld\n", 
            status);
        return 1;
    }

    wprintf(L"LookupPersistentTcpPortReservation call succeeded\n");
    wprintf(L"  Token = %I64d\n", resToken);  
  
    // Comment out this block if you don't want to create a socket and associate it with the 
    // persistent reservation

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        wprintf(L"WSAStartup failed with error = %d\n", iResult);
        return 1;
    }

    sock = socket(iFamily, iType, iProtocol);
    if (sock == INVALID_SOCKET)
        wprintf(L"socket function failed with error = %d\n", WSAGetLastError());
    else {
        wprintf(L"socket function succeeded\n");

        iResult =
            WSAIoctl(sock, SIO_ASSOCIATE_PORT_RESERVATION, (LPVOID) & resToken,
                     sizeof (ULONG64), NULL, 0, &bytesReturned, NULL, NULL);
        if (iResult != 0) {
            wprintf
                (L"WSAIoctl(SIO_ASSOCIATE_PORT_RESERVATION) failed with error = %d\n",
                 WSAGetLastError());
        } else {
            wprintf(L"WSAIoctl(SIO_ASSOCIATE_PORT_RESERVATION) succeeded, bytesReturned = %u\n", 
                bytesReturned);                

            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = 0;

            iResult = bind(sock, (SOCKADDR*) &service, sizeof(service) );
            if (iResult == SOCKET_ERROR)
                wprintf(L"bind failed with error = %d\n", WSAGetLastError());
            else {
                wprintf(L"bind succeeded\n");
                iResult = getsockname(sock, (SOCKADDR*) &sockName, &nameLen);
                if (iResult == SOCKET_ERROR) 
                    wprintf(L"getsockname failed with error = %d\n", WSAGetLastError() );
                else {
                    wprintf(L"getsockname succeeded\n");
                    wprintf(L"Port number allocated = %u\n", ntohs(sockName.sin_port) );
                }
            }                  
        }

        if (sock != INVALID_SOCKET) {
            iResult = closesocket(sock);
            if (iResult == SOCKET_ERROR) {
                wprintf(L"closesocket failed with error = %d\n", WSAGetLastError());
            }
        }
    }
    WSACleanup();

    return 0;
}

Requisitos

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

Confira também

CreatePersistentTcpPortReservation

CreatePersistentUdpPortReservation

DeletePersistentTcpPortReservation

DeletePersistentUdpPortReservation

LookupPersistentUdpPortReservation

SIO_ASSOCIATE_PORT_RESERVATION