Getting UDP state list

Using GetUdpTable(), information about opened UDP ports in the local windows machine can be obtained. In this page, usage of GetUdpTable() is shown.

Sample code

The following sample code shows how to use GetUdpTable().


#include <stdio.h>

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

int
main()
{
 DWORD i;
 PMIB_UDPTABLE pUdpTable;
 DWORD dwSize = 0;
 DWORD dwRetVal = 0;

 char *addr_ptr;
 unsigned short *port_ptr;

 /* Get size required by GetUdpTable() */
 if (GetUdpTable(NULL, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
   pUdpTable = (MIB_UDPTABLE *) malloc (dwSize);
 }

 /* Get actual data using GetUdpTable() */
 if ((dwRetVal = GetUdpTable(pUdpTable, &dwSize, 0))
      == NO_ERROR) {
   if (pUdpTable->dwNumEntries > 0) {
     for (i=0; i<pUdpTable->dwNumEntries; i++) {
       addr_ptr = (char *)&pUdpTable->table[i].dwLocalAddr;
       printf("Local Address: %s\n",
        inet_ntoa(*(struct in_addr *)addr_ptr));

       port_ptr = (unsigned short *)&pUdpTable->table[i].dwLocalPort;
       printf("Local Port:    %ld\n",
         htons(*port_ptr));

       printf("\n");
     }
   }
 } else {
   printf("GetUdpTable failed.\n");
   LPVOID lpMsgBuf;
			
   if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                     FORMAT_MESSAGE_FROM_SYSTEM | 
                     FORMAT_MESSAGE_IGNORE_INSERTS,
                     NULL,
                     dwRetVal,
                     MAKELANGID(LANG_NEUTRAL,
                                SUBLANG_DEFAULT), //Default language
                     (LPTSTR) &lpMsgBuf,
                     0,
                     NULL ))  {
                       printf("\tError: %s", lpMsgBuf);
   }

   LocalFree( lpMsgBuf );
 }

 return 0;
}

Sample code output

The sample will output an message like the following.


C:> a.exe
Local Address: 0.0.0.0
Local Port:    1028

Local Address: 127.0.0.1
Local Port:    123

Local Address: 127.0.0.1
Local Port:    1876

Local Address: 0.0.0.0
Local Port:    1026

Structure used by GetUdpTable()

The following structure is MIB_UDPTABLE that is used by GetUdpTable().


typedef struct _MIB_UDPROW {
  DWORD dwLocalAddr;
  DWORD dwLocalPort;
} MIB_UDPROW, *PMIB_UDPROW;

typedef struct _MIB_UDPTABLE {
  DWORD dwNumEntries;
  MIB_UDPROW table[ANY_SIZE];
} MIB_UDPTABLE, *PMIB_UDPTABLE;

MIB_UDPROW

dwLocalAddr Local IP address (IPv4) that the UDP port is bind to.
dwLocalPort UDP port number.

MIB_UDPTABLE

dwNumEntries Number of UDP entries.
table UDP entry information is stored as array of MIB_UDPROW. The length of array is shown in dwNumEntries.

  

Copyright (C) GeekPage.JP. All rights reserved.