(摘抄)一个C++类:枚举主机的网卡

本文介绍了一个C++类CInterface,用于枚举主机的网络接口。该类利用WSAIoctl函数获取接口信息,通过初始化、内存管理和错误处理确保功能的正确执行。接口信息存储在INTERFACE_INFO结构体中,包含了接口标志、地址、广播地址和子网掩码等详细信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘抄自DSshow的filter例子DSNetwork

 

CInterface.h

 

class CInterface

{

    enum {

        NUM_NIC_FIRST_GUESS = 3,    //  1 NIC, 1 loopback, 1 extra
        MAX_SUPPORTED_IFC   = 32
    } ;

 

    INTERFACE_INFO *    m_pNIC ;
    ULONG               m_cNIC ;
    HANDLE              m_hHeap ;

 

    public :

        CInterface ( ) ;

 

        ~CInterface ( ) ;

 

        BOOL IsInitialized ( ) ;

       

        HRESULT Initialize ( ) ;

       

        INTERFACE_INFO * operator [] ( ULONG i );

};

--------------------------------------------------------------------------------------------------------------------------------------------

INTERFACE_INFO Structure:

 

The INTERFACE_INFO structure is used in conjunction with the SIO_GET_INTERFACE_LIST ioctl command to

 

obtain information about an interface IP address.

 

#include < Ws2tcpip.h >

typedef struct _INTERFACE_INFO {
  u_long             iiFlags;
  sockaddr_gen  iiAddress;
  sockaddr_gen  iiBroadcastAddress;
  sockaddr_gen  iiNetmask;
} INTERFACE_INFO, FAR * LPINTERFACE_INFO;

 

 

iiFlags           A bitmask describing the status of the interface. The following flags are possible.
FlagMeaning

IFF_UP

The interface is running.

IFF_BROADCAST

The broadcast feature is supported.

IFF_LOOPBACK

The loopback interface is running.

IFF_POINTTOPOINT

The interface is using point-to-point link.

IFF_MULTICAST

The multicast feature is supported.

iiAddress

Address of an interface.

iiBroadcastAddress

Broadcast address of the interface or the address of the other side for point-to-point links.

iiNetmask

Netmask used by the interface.

 

 

 

==============================================================================

 

CInterface.cpp

 

CInterface::CInterface (
    ) : m_pNIC  (NULL),
        m_hHeap (NULL) {}

 

CInterface::~CInterface ( )
{
    if (m_pNIC) {
        ASSERT (m_hHeap) ;
        HeapFree (m_hHeap, NULL, m_pNIC) ;
    }
}

 

 

 

BOOL CInterface::IsInitialized ( )
{
    return m_pNIC != NULL ;
}

 

HRESULT CInterface::Initialize ( )
{
    SOCKET  sock ;
    DWORD   retval ;
    WSADATA wsadata ;
    ULONG   size ;

 

    //  can't initialize twice
    if (m_pNIC) {
        return HRESULT_FROM_WIN32 (ERROR_GEN_FAILURE) ;
    }

/*

 

HRESULTl_FROM_WIN32 Macro

    

          Maps a system error code to an HRESULT value.

Syntax

       HRESULT HRESULT_FROM_WIN32( DWORD x );

Parameters 

The system error code.

Return Value

          The HRESULT value.

*/

 

    //  initialize local variables
    sock = INVALID_SOCKET ;

    m_hHeap = GetProcessHeap () ;

/*

GetProcessHeap function

 

Retrieves a handle to the heap of the calling process. The handle can then be used in subsequent calls

 

to the heap function.

 

Syntax

 

HANDLE WINAPI GetProcessHeap(void);

 

Return Value

 

If the function succeeds, the return value is a handle to the calling process's heap.

 

If the function fails, the return value is NULL. To get extended error information, Call GetLastError function.

 

*/


    if (m_hHeap == NULL) {
        retval = GetLastError () ;
        return HRESULT_FROM_WIN32 (retval) ;
    }

    if (WSAStartup (MAKEWORD(2, 0), & wsadata)) {
        retval = WSAGetLastError () ;
        return HRESULT_FROM_WIN32 (retval) ;
    }

 

    sock = WSASocket (AF_INET,
                      SOCK_RAW,
                      IPPROTO_RAW,
                      NULL,
                      0,
                      NULL) ;
    if (sock == INVALID_SOCKET) {
        retval = WSAGetLastError () ;
        goto error ;
    }

    for (m_cNIC = NUM_NIC_FIRST_GUESS;; m_cNIC++) {

        size = m_cNIC * sizeof INTERFACE_INFO ;

        __try {

            m_pNIC = reinterpret_cast <INTERFACE_INFO *> (m_pNIC ? HeapReAlloc (m_hHeap, HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS, m_pNIC, size) :
                                                                   HeapAlloc (m_hHeap, HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS, size)) ;

        } __except (EXCEPTION_EXECUTE_HANDLER) {

            retval = ERROR_NOT_ENOUGH_MEMORY ;
            goto error ;
        }

        // make the call
        if (WSAIoctl (sock,
                      SIO_GET_INTERFACE_LIST,
                      NULL,
                      0,
                      m_pNIC,
                      size,
                      & size,
                      NULL,
                      NULL) == 0) {

            //  call succeeded
            m_cNIC = size / sizeof INTERFACE_INFO ;
            break ;
        }

 

/*

*     WSAIoctl Function

*

*  The WSAIoctl function control the mode of a socket.

*

*syntax

*

*   int WSAIoctl (

*        __in SOCKET S,

*        __in DWORD dwIoControlCode,

*        __in LPVOID LpvInBuffer,

*        __in DWORD cbInBuffer,

*        __in LPVOID LpvOutBuffer,

*        __in DWORD cbOutBuffer,

*        __out LPDWORD lpcbBytesReturned,
*        __in  LPWSAOVERLAPPED lpOverlapped,
*        __in  LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
*

*

*parameters

*

*

s         A descriptor identifying a socket. dwIoControlCode

The control code of operation to perform.

lpvInBuffer

A pointer to the input buffer.

cbInBuffer

The size, in bytes, of the input buffer.

lpvOutBuffer

A pointer to the output buffer.

cbOutBuffer

The size, in bytes, of the output buffer.

lpcbBytesReturned

A pointer to actual number of bytes of output.

lpOverlapped

A pointer to a WSAOVERLAPPED structure (ignored for non-overlapped sockets).

lpCompletionRoutine

A pointer to the completion routine called when the operation has been completed (ignored for non-overlapped sockets).

 

Remarks

 

SIO_GET_INTERFACE_LIST (opcode setting: O, T==0)

Returns a list of configured IP interfaces and their parameters as an array of INTERFACE_INFO structures.

Note  Support of this command is mandatory for Windows Sockets 2-compliant TCP/IP service providers.

The lpvOutBuffer parameter points to the buffer in which to store the information about interfaces as an array of INTERFACE_INFO structures for unicast IP addresses on the interfaces. The cbOutBuffer parameter specifies the length of the output buffer. The number of interfaces returned (number of structures returned in the buffer pointed to by lpvOutBuffer parameter) can be determined based on the actual length of the output buffer returned in lpcbBytesReturned parameter.

If the WSAIoctl function is called with SIO_GET_INTERFACE_LIST and the level member of the socket s parameter is not defined as IPPROTO_IP, WSAEINVAL is returned. A call to the WSAIoctl function with SIO_GET_INTERFACE_LIST returns WSAEFAULT if the cbOutBuffer parameter that specifies the length of the output buffer is too small ro receive the list of configured interfaces.

*/

        // have we reached MAX_SUPPORTED_IFC
        if (m_cNIC == MAX_SUPPORTED_IFC) {

            m_cNIC = 0 ;
            retval = ERROR_GEN_FAILURE ;
            goto error ;
        }
    }

    WSACleanup () ;
    return S_OK ;

error :

    if (m_pNIC) {
        ASSERT (m_hHeap) ;
        HeapFree (m_hHeap, NULL, m_pNIC) ;
        m_pNIC = NULL ;
    }

    if (sock != INVALID_SOCKET) {
        closesocket (sock) ;
    }

    WSACleanup () ;

    return HRESULT_FROM_WIN32 (retval) ;
}

INTERFACE_INFO *
CInterface::operator [] (
    ULONG i
    )
{
    if (i >= m_cNIC) {
        return NULL ;
    }

    return & m_pNIC [i] ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值