Share via


列舉所有路由

下列程式概述用來列舉 RTMv2 API 所使用之任何實體的步驟。 下列範例程式碼示範如何列舉所有路由。

每個列舉的基本程式如下

  1. 從路由表管理員取得控制碼,以啟動列舉。 呼叫 RtmCreateDestEnumRtmCreateRouteEnumRtmCreateNextHopEnum 以提供指定所列舉資訊的準則。 此準則包括但不限於目的地範圍、特定介面,以及資訊所在的檢視。
  2. 呼叫 RtmGetEnumDestsRtmGetEnumRoutesRtmGetEnumNextHops 一或多次來擷取資料,直到路由表管理員傳回ERROR_NO_MORE_ITEMS為止。 如果列舉路由) ,則會依位址資訊 (和喜好設定和計量值的順序傳回路由、目的地和下一個躍點資料。
  3. 不再需要與列舉相關聯的控制碼或資訊結構時,呼叫 RtmReleaseDestsRtmReleaseRoutesRtmReleaseNextHops
  4. 呼叫 RtmDeleteEnumHandle 以釋放建立列舉時傳回的列舉控制碼。 此函式可用來釋放所有類型的列舉控制碼。

注意

只有在用戶端使用 RTM_VIEW_MASK_ANY 從所有檢視要求資料時,才會列舉處於保留狀態的路由。

 

下列範例程式碼示範如何列舉路由表中的所有路由。

MaxHandles = RegnProfile.MaxHandlesInEnum;

RouteHandles = _alloca(MaxHandles * sizeof(HANDLE));

// Do a "route enumeration" over the whole table
// by passing a NULL DestHandle in this function.

DestHandle = NULL; // Give a valid handle to enumerate over a particular destination

Status = RtmCreateRouteEnum(RtmRegHandle,
                            DestHandle,
                            RTM_VIEW_MASK_UCAST|RTM_VIEW_MASK_MCAST,
                            RTM_ENUM_OWN_ROUTES, // Get only your own routes
                            NULL,
                            0,
                            NULL,
                            0,
                            &EnumHandle2);
if (Status == NO_ERROR)
{
    do
    {
        NumHandles = MaxHandles;

        Status = RtmGetEnumRoutes(RtmRegHandle
                                  EnumHandle2,
                                  &NumHandles,
                                  RouteHandles);

        for (k = 0; k < NumHandles; k++)
        {
            wprintf("Route %d: %p\n", l++, RouteHandles[k]);

            // Get route information using the route's handle
            Status = RtmGetRouteInfo(...RouteHandles[k]...);

            if (Status == NO_ERROR)
            {
                // Do whatever you want with the route info
                //...

                // Release the route information once you are done
                RtmReleaseRouteInfo(...);
            }
        }

        RtmReleaseRoutes(RtmRegHandle, NumHandles, RouteHandles);
    }
    while (Status == NO_ERROR)

    // Close the enumeration and release its resources
    RtmDeleteEnumHandle(RtmRegHandle, EnumHandle2);
}