본문 바로가기
MFC

Ethernet Status Check WinAPI

by leo21c 2019. 7. 2.
SMALL

참조)

https://docs.microsoft.com/ko-kr/windows/win32/api/netioapi/nf-netioapi-getifentry2

 

GetIfEntry2 function (netioapi.h)

Retrieves information for the specified interface on the local computer.

docs.microsoft.com

https://msdn.microsoft.com/zh-tw/visualc/aa365917(v=vs.90)

 

GetAdaptersInfo function (Windows)

The GetAdaptersInfo function retrieves adapter information for the local computer. On Windows XP and later:  Use the GetAdaptersAddresses function instead of GetAdaptersInfo. Syntax DWORD GetAdaptersInfo( _Out_   PIP_ADAPTER_INFO pAdapterInfo, _Inout_ PULO

msdn.microsoft.com

이더넷의 LAN 연결 상태를 확인하기 위해서 만들어 본 함수이다.

 

필요한 헤더와 LIB는 아래와 같다.
참조사이트를 보고 추가했다.

#include  <winsock2.h>
#include  <ws2tcpip.h>
#include  <iphlpapi.h>

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

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

// Need to link with Ole32.lib to print GUID
#pragma comment(lib, "ole32.lib")

아래는 체크 함수이다.

void checkEthernetPortStatus()
{
   ULONG retVal = 0;
   ULONG ifIndex;

   MIB_IF_ROW2 ifRow;

   DWORD dwNumIf = 0;
   GetNumberOfInterfaces(&dwNumIf);

   for (int i = 1; i < dwNumIf; i++)
   {
      // Make sure the ifRow is zeroed out
      SecureZeroMemory((PVOID)&ifRow, sizeof(MIB_IF_ROW2));

      ifIndex = i;// _wtoi(argv[1]);

      ifRow.InterfaceIndex = ifIndex;
      retVal = GetIfEntry2(&ifRow);

      if (retVal != NO_ERROR) {
         wprintf(L"GetIfEntry returned error: %lu\n", retVal);
         exit(1);
      }
      else
         wprintf(L"GetIfEntry2 function returned okay\n");

      if (ifRow.Type == MIB_IF_TYPE_ETHERNET &&
         ifRow.InterfaceAndOperStatusFlags.HardwareInterface == TRUE)
      {
         switch (ifRow.MediaConnectState)
         {
            case MediaConnectStateConnected:
               TRACE(_T("WAN 어뎁터가 연결됨! [%s]\n"), ifRow.Description);
               break;
            case MediaConnectStateDisconnected:
               TRACE(_T("LAN 어뎁터가 연결끈김! [%s]\n"), ifRow.Description);
               break;
            case MediaConnectStateUnknown:
               TRACE(_T("WAN 어뎁터 상태 모름! [%s]\n"), ifRow.Description);
               break;
         }
      }
   }
}

GetNumberOfInterfaces() 함수를 이용해서 Interface의 전체 개수를 확인한다.
for loop를 돌면서 GetIfEntry2()를 이용해서 interface 이름과 상태 값을 가지고 온다.

InterfaceAndOperStatusFlags.HardwareInterface를 비교하는 구문이 없으면 Logical interface도 비교를 하기 때문에 추가를 해야 한다.

 

위와 같이 함수를 돌리면 HW Interface의 Port 연결 여부를 확인할 수 있다.

 

LIST