Win32 API 日本語リファレンス
ホームNetworkManagement.IpHelper › SetIpForwardEntry

SetIpForwardEntry

関数
IPv4ルーティングテーブルの既存経路エントリを変更する。
DLLIPHLPAPI.dll呼出規約winapi対応OSWindows 2000 以降

シグネチャ

// IPHLPAPI.dll
#include <windows.h>

DWORD SetIpForwardEntry(
    MIB_IPFORWARDROW* pRoute
);

パラメーター

名前方向説明
pRouteMIB_IPFORWARDROW*in既存ルートの新しい情報を指定する MIB_IPFORWARDROW 構造体へのポインター。呼び出し元は、この構造体の dwForwardProto メンバーに MIB_IPPROTO_NETMGMT を指定する必要があります。また、呼び出し元は構造体の dwForwardIfIndexdwForwardDestdwForwardMaskdwForwardNextHop、および dwForwardPolicy の各メンバーに値を指定する必要があります。

戻り値の型: DWORD

公式ドキュメント

SetIpForwardEntry 関数は、ローカルコンピューターの IPv4 ルーティングテーブル内の既存のルートを変更します。

戻り値

関数が成功した場合、戻り値は NO_ERROR です。

関数が失敗した場合、戻り値は次のいずれかのエラーコードです。

Return code Description
ERROR_ACCESS_DENIED
アクセスが拒否されました。このエラーは、Windows Vista および Windows Server 2008 において、次のような複数の条件下で返されます。ユーザーがローカルコンピューターで必要な管理者権限を持っていない場合、またはアプリケーションが組み込み Administrator として昇格されたシェル(管理者として実行)で実行されていない場合です。
ERROR_FILE_NOT_FOUND
指定されたファイルが見つかりません。このエラーは、Windows Vista 以降において、pRoute パラメーターが指す MIB_IPFORWARDROW 構造体の dwForwardIfIndex メンバーで指定されたネットワークインターフェイスが見つからなかった場合に返されます。
ERROR_INVALID_PARAMETER
pRoute パラメーターが NULL であるか、SetIpForwardEntrypRoute の指すメモリから読み取れないか、あるいは MIB_IPFORWARDROW 構造体のメンバーのいずれかが無効です。
ERROR_NOT_FOUND
要素が見つかりません。このエラーは、Windows Vista 以降において、同じ IPv4 ルートテーブルエントリに対して DeleteIpForwardEntry 関数を呼び出した後に SetIpForwardEntry 関数を呼び出した場合に返されます。
ERROR_NOT_SUPPORTED
要求はサポートされていません。この値は、ローカルコンピューターで IPv4 トランスポートが構成されていない場合に返されます。このエラーは、Windows Server 2003 以前において、ローカルコンピューターに TCP/IP スタックが構成されていない場合にも返されます。
Other
返されたエラーのメッセージ文字列を取得するには、 FormatMessage を使用してください。

解説(Remarks)

route パラメーターが指す MIB_IPFORWARDROW 構造体の dwForwardProto メンバーは MIB_IPPROTO_NETMGMT に設定する必要があります。そうしないと SetIpForwardEntry は失敗します。ルーティングプロトコル識別子は、指定したルーティングプロトコルのルート情報を識別するために使用されます。たとえば、MIB_IPPROTO_NETMGMT は、Dynamic Host Configuration Protocol (DHCP)、Simple Network Management Protocol (SNMP) などのネットワーク管理を通じて設定された IP ルーティングのルート情報、または CreateIpForwardEntryDeleteIpForwardEntrySetIpForwardEntry 関数の呼び出しによるルート情報を識別するために使用されます。

Windows Vista および Windows Server 2008 では、pRoute パラメーターが指す MIB_IPFORWARDROW 構造体の dwForwardMetric1 メンバーで指定されるルートメトリックは、ルートメトリックに、関連するインターフェイスの MIB_IPINTERFACE_ROW 構造体の Metric メンバーで指定されたインターフェイスメトリックを加算した合計値を表します。したがって、MIB_IPFORWARDROW 構造体の dwForwardMetric1 メンバーは、関連する MIB_IPINTERFACE_ROW 構造体の Metric メンバー以上である必要があります。アプリケーションがルートメトリックを 0 に設定したい場合は、MIB_IPFORWARDROW 構造体の dwForwardMetric1 メンバーを、関連する MIB_IPINTERFACE_ROW 構造体の Metric メンバーで指定されたインターフェイスメトリックの値と等しく設定する必要があります。アプリケーションは、GetIpInterfaceEntry 関数を呼び出すことでインターフェイスメトリックを取得できます。

Windows Vista および Windows Server 2008 では、SetIpForwardEntry 関数は単一のサブインターフェイスを持つインターフェイス(インターフェイス LUID とサブインターフェイス LUID が同じ場合)でのみ動作します。MIB_IPFORWARDROW 構造体の dwForwardIfIndex メンバーがインターフェイスを指定します。

route パラメーターが指す MIB_IPFORWARDROW 構造体の dwForwardAge メンバーは、現在 SetIpForwardEntry では使用されていません。dwForwardAge メンバーは、Routing and Remote Access Service (RRAS) が実行されている場合にのみ、かつ Protocol Identifiers リファレンスページで定義されている MIB_IPPROTO_NETMGMT 型のルートに対してのみ使用されます。dwForwardAgeINFINITE に設定されている場合、ルートはタイムアウト値に基づいて削除されることはありません。

dwForwardAge のそれ以外の値は、TCP/IP スタックがネットワークルーティングテーブルからルートを削除するまでの秒数を指定します。

SetIpForwardEntry によって変更されたルートは、dwForwardAge の既定値として自動的に INFINITE を持ちます。

route パラメーターが指す MIB_IPFORWARDROW 構造体の多くのメンバーは、現在 SetIpForwardEntry では使用されていません。これらのメンバーには、dwForwardPolicydwForwardTypedwForwardAgedwForwardNextHopASdwForwardMetric1dwForwardMetric2dwForwardMetric3dwForwardMetric4、および dwForwardMetric5 が含まれます。

IP ルーティングテーブルに新しいルートを作成するには、 CreateIpForwardEntry 関数を使用します。IP ルーティングテーブルを取得するには、GetIpForwardTable 関数を呼び出します。

Windows Vista 以降では、SetIpForwardEntry 関数は Administrators グループのメンバーとしてログオンしているユーザーのみが呼び出せます。Administrators グループのメンバーでないユーザーが SetIpForwardEntry を呼び出した場合、関数呼び出しは失敗し、ERROR_ACCESS_DENIED が返されます。

この関数は、Windows Vista 以降のユーザーアカウント制御 (UAC) が原因で失敗することもあります。この関数を含むアプリケーションが、組み込み Administrator 以外の Administrators グループのメンバーとしてログオンしているユーザーによって実行された場合、アプリケーションのマニフェストファイルで requestedExecutionLevel が requireAdministrator に設定されていない限り、この呼び出しは失敗します。アプリケーションにこのマニフェストファイルがない場合、組み込み Administrator 以外の Administrators グループのメンバーとしてログオンしているユーザーは、この関数を成功させるために、組み込み Administrator として昇格されたシェル(管理者として実行)でアプリケーションを実行する必要があります。

Note Windows NT 4.0 および Windows 2000 以降では、この関数は特権操作を実行します。この関数を正常に実行するには、呼び出し元が Administrators グループまたは NetworkConfigurationOperators グループのメンバーとしてログオンしている必要があります。

Examples

次の例は、既定のゲートウェイを NewGateway に変更する方法を示しています。単に GetIpForwardTable を呼び出してゲートウェイを変更し、その後 SetIpForwardEntry を呼び出しても、ルートは変更されず、新しいルートが追加されるだけです。何らかの理由で複数の既定ゲートウェイが存在する場合、このコードはそれらをすべて削除します。新しいゲートウェイは有効である必要があることに注意してください。そうでない場合、TCP/IP は変更を無視します。

Note このコードを実行すると IP ルーティングテーブルが変更され、ネットワーク通信が失敗する可能性が高くなります。

Windows Vista 以降: Windows Vista 以降で同じルートテーブルエントリに対して DeleteIpForwardEntry 関数を呼び出した後に SetIpForwardEntry 関数を呼び出すと、ERROR_NOT_FOUND が返されます。Windows Vista 以降でこの例を再現する正しい方法は、CreateIpForwardEntry 関数を使用して新しいルートテーブルエントリを作成し、その後 DeleteIpForwardEntry 関数を呼び出して古いルートテーブルエントリを削除することです。

#pragma comment(lib, "IPHLPAPI.lib")

// #ifndef WIN32_LEAN_AND_MEAN
// #define WIN32_LEAN_AND_MEAN
// #endif

// #pragma warning(push)
// #pragma warning(disable: 4127)

// #include <windows.h>

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

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
/* Note: could also use malloc() and free() */

int main()
{

    // Declare and initialize variables.

    /* variables used for SetIfForwardEntry */

    PMIB_IPFORWARDTABLE pIpForwardTable = NULL;
    PMIB_IPFORWARDROW pRow = NULL;
    DWORD dwSize = 0;
    BOOL bOrder = FALSE;
    DWORD dwStatus = 0;
    DWORD NewGateway = 0xDDBBCCAA;      // this is in host order Ip Address AA.BB.CC.DD is DDCCBBAA
    DWORD i;

// Find out how big our buffer needs to be.
    dwStatus = GetIpForwardTable(pIpForwardTable, &dwSize, bOrder);
    if (dwStatus == ERROR_INSUFFICIENT_BUFFER) {
        // Allocate the memory for the table
        pIpForwardTable = (PMIB_IPFORWARDTABLE) malloc(dwSize);
        if (pIpForwardTable == NULL) {
            printf("Unable to allocate memory for the IPFORWARDTALE\n");
            exit(1);
        }
        // Now get the table.
        dwStatus = GetIpForwardTable(pIpForwardTable, &dwSize, bOrder);
    }

    if (dwStatus != ERROR_SUCCESS) {
        printf("getIpForwardTable failed.\n");
        if (pIpForwardTable)
            free(pIpForwardTable);
        exit(1);
    }
// Search for the row in the table we want. The default gateway has a destination
// of 0.0.0.0. Notice that we continue looking through the table, but copy only
// one row. This is so that if there happen to be multiple default gateways, we can
// be sure to delete them all.
    for (i = 0; i < pIpForwardTable->dwNumEntries; i++) {
        if (pIpForwardTable->table[i].dwForwardDest == 0) {
            // We have found the default gateway.
            if (!pRow) {
                // Allocate some memory to store the row in. This is easier than filling
                // in the row structure ourselves, and we can be sure to change only the
                // gateway address.
                pRow = (PMIB_IPFORWARDROW) malloc(sizeof (MIB_IPFORWARDROW));
                if (!pRow) {
                    printf("Malloc failed. Out of memory.\n");
                    exit(1);
                }
                // Copy the row.
                memcpy(pRow, &(pIpForwardTable->table[i]),
                       sizeof (MIB_IPFORWARDROW));
            }
            // Delete the old default gateway entry.
            dwStatus = DeleteIpForwardEntry(&(pIpForwardTable->table[i]));

            if (dwStatus != ERROR_SUCCESS) {
                printf("Could not delete old gateway\n");
                exit(1);
            }
        }
    }

// Set the nexthop field to our new gateway. All the other properties of the route will
// be the same as they were previously.
    pRow->dwForwardNextHop = NewGateway;

// Create a new route entry for the default gateway.
    dwStatus = SetIpForwardEntry(pRow);

    if (dwStatus == NO_ERROR)
        printf("Gateway changed successfully\n");
    else if (dwStatus == ERROR_INVALID_PARAMETER)
        printf("Invalid parameter.\n");
    else
        printf("Error: %d\n", dwStatus);

// Free resources.
    if (pIpForwardTable)
        free(pIpForwardTable);
    if (pRow)
        free(pRow);
}

出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// IPHLPAPI.dll
#include <windows.h>

DWORD SetIpForwardEntry(
    MIB_IPFORWARDROW* pRoute
);
[DllImport("IPHLPAPI.dll", ExactSpelling = true)]
static extern uint SetIpForwardEntry(
    IntPtr pRoute   // MIB_IPFORWARDROW*
);
<DllImport("IPHLPAPI.dll", ExactSpelling:=True)>
Public Shared Function SetIpForwardEntry(
    pRoute As IntPtr   ' MIB_IPFORWARDROW*
) As UInteger
End Function
' pRoute : MIB_IPFORWARDROW*
Declare PtrSafe Function SetIpForwardEntry Lib "iphlpapi" ( _
    ByVal pRoute As LongPtr) As Long
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

SetIpForwardEntry = ctypes.windll.iphlpapi.SetIpForwardEntry
SetIpForwardEntry.restype = wintypes.DWORD
SetIpForwardEntry.argtypes = [
    ctypes.c_void_p,  # pRoute : MIB_IPFORWARDROW*
]
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('IPHLPAPI.dll')
SetIpForwardEntry = Fiddle::Function.new(
  lib['SetIpForwardEntry'],
  [
    Fiddle::TYPE_VOIDP,  # pRoute : MIB_IPFORWARDROW*
  ],
  -Fiddle::TYPE_INT)
#[link(name = "iphlpapi")]
extern "system" {
    fn SetIpForwardEntry(
        pRoute: *mut MIB_IPFORWARDROW  // MIB_IPFORWARDROW*
    ) -> u32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[DllImport("IPHLPAPI.dll")]
public static extern uint SetIpForwardEntry(IntPtr pRoute);
"@
$api = Add-Type -MemberDefinition $sig -Name 'IPHLPAPI_SetIpForwardEntry' -Namespace Win32 -PassThru
# $api::SetIpForwardEntry(pRoute)
#uselib "IPHLPAPI.dll"
#func global SetIpForwardEntry "SetIpForwardEntry" sptr
; SetIpForwardEntry varptr(pRoute)   ; 戻り値は stat
; pRoute : MIB_IPFORWARDROW* -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
出力引数:
#uselib "IPHLPAPI.dll"
#cfunc global SetIpForwardEntry "SetIpForwardEntry" var
; res = SetIpForwardEntry(pRoute)
; pRoute : MIB_IPFORWARDROW* -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
出力引数:
; DWORD SetIpForwardEntry(MIB_IPFORWARDROW* pRoute)
#uselib "IPHLPAPI.dll"
#cfunc global SetIpForwardEntry "SetIpForwardEntry" var
; res = SetIpForwardEntry(pRoute)
; pRoute : MIB_IPFORWARDROW* -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	iphlpapi = windows.NewLazySystemDLL("IPHLPAPI.dll")
	procSetIpForwardEntry = iphlpapi.NewProc("SetIpForwardEntry")
)

// pRoute (MIB_IPFORWARDROW*)
r1, _, err := procSetIpForwardEntry.Call(
	uintptr(pRoute),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // DWORD
function SetIpForwardEntry(
  pRoute: Pointer   // MIB_IPFORWARDROW*
): DWORD; stdcall;
  external 'IPHLPAPI.dll' name 'SetIpForwardEntry';
result := DllCall("IPHLPAPI\SetIpForwardEntry"
    , "Ptr", pRoute   ; MIB_IPFORWARDROW*
    , "UInt")   ; return: DWORD
●SetIpForwardEntry(pRoute) = DLL("IPHLPAPI.dll", "dword SetIpForwardEntry(void*)")
# 呼び出し: SetIpForwardEntry(pRoute)
# pRoute : MIB_IPFORWARDROW* -> "void*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

extern "iphlpapi" fn SetIpForwardEntry(
    pRoute: [*c]MIB_IPFORWARDROW // MIB_IPFORWARDROW*
) callconv(std.os.windows.WINAPI) u32;
proc SetIpForwardEntry(
    pRoute: ptr MIB_IPFORWARDROW  # MIB_IPFORWARDROW*
): uint32 {.importc: "SetIpForwardEntry", stdcall, dynlib: "IPHLPAPI.dll".}
pragma(lib, "iphlpapi");
extern(Windows)
uint SetIpForwardEntry(
    MIB_IPFORWARDROW* pRoute   // MIB_IPFORWARDROW*
);
ccall((:SetIpForwardEntry, "IPHLPAPI.dll"), stdcall, UInt32,
      (Ptr{MIB_IPFORWARDROW},),
      pRoute)
# pRoute : MIB_IPFORWARDROW* -> Ptr{MIB_IPFORWARDROW}
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
uint32_t SetIpForwardEntry(
    void* pRoute);
]]
local iphlpapi = ffi.load("iphlpapi")
-- iphlpapi.SetIpForwardEntry(pRoute)
-- pRoute : MIB_IPFORWARDROW*
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('IPHLPAPI.dll');
const SetIpForwardEntry = lib.func('__stdcall', 'SetIpForwardEntry', 'uint32_t', ['void *']);
// SetIpForwardEntry(pRoute)
// pRoute : MIB_IPFORWARDROW* -> 'void *'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("IPHLPAPI.dll", {
  SetIpForwardEntry: { parameters: ["pointer"], result: "u32" },
});
// lib.symbols.SetIpForwardEntry(pRoute)
// pRoute : MIB_IPFORWARDROW* -> "pointer"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
uint32_t SetIpForwardEntry(
    void* pRoute);
C, "IPHLPAPI.dll");
// $ffi->SetIpForwardEntry(pRoute);
// pRoute : MIB_IPFORWARDROW*
// 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
// WINAPI(stdcall): x64 では呼出規約が統一されるため問題なし。x86 では __stdcall 対応のラッパが必要な場合あり。
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

public interface Iphlpapi extends StdCallLibrary {
    Iphlpapi INSTANCE = Native.load("iphlpapi", Iphlpapi.class);
    int SetIpForwardEntry(
        Pointer pRoute   // MIB_IPFORWARDROW*
    );
}
@[Link("iphlpapi")]
lib LibIPHLPAPI
  fun SetIpForwardEntry = SetIpForwardEntry(
    pRoute : MIB_IPFORWARDROW*   # MIB_IPFORWARDROW*
  ) : UInt32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef SetIpForwardEntryNative = Uint32 Function(Pointer<Void>);
typedef SetIpForwardEntryDart = int Function(Pointer<Void>);
final SetIpForwardEntry = DynamicLibrary.open('IPHLPAPI.dll')
    .lookupFunction<SetIpForwardEntryNative, SetIpForwardEntryDart>('SetIpForwardEntry');
// pRoute : MIB_IPFORWARDROW* -> Pointer<Void>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function SetIpForwardEntry(
  pRoute: Pointer   // MIB_IPFORWARDROW*
): DWORD; stdcall;
  external 'IPHLPAPI.dll' name 'SetIpForwardEntry';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "SetIpForwardEntry"
  c_SetIpForwardEntry :: Ptr () -> IO Word32
-- pRoute : MIB_IPFORWARDROW* -> Ptr ()
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let setipforwardentry =
  foreign "SetIpForwardEntry"
    ((ptr void) @-> returning uint32_t)
(* pRoute : MIB_IPFORWARDROW* -> (ptr void) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library iphlpapi (t "IPHLPAPI.dll"))
(cffi:use-foreign-library iphlpapi)

(cffi:defcfun ("SetIpForwardEntry" set-ip-forward-entry :convention :stdcall) :uint32
  (p-route :pointer))   ; MIB_IPFORWARDROW*
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $SetIpForwardEntry = Win32::API::More->new('IPHLPAPI',
    'DWORD SetIpForwardEntry(LPVOID pRoute)');
# my $ret = $SetIpForwardEntry->Call($pRoute);
# pRoute : MIB_IPFORWARDROW* -> LPVOID
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

類似 API
公式の関連項目
使用する型