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

GetTcpStatistics

関数
TCPプロトコルの統計情報を取得する。
DLLIPHLPAPI.dll呼出規約winapi対応OSWindows 2000 以降

シグネチャ

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

DWORD GetTcpStatistics(
    MIB_TCPSTATS_LH* Statistics
);

パラメーター

名前方向説明
StatisticsMIB_TCPSTATS_LH*outローカルコンピューターの TCP 統計情報を受け取る MIB_TCPSTATS 構造体へのポインター。

戻り値の型: DWORD

公式ドキュメント

GetTcpStatistics 関数は、ローカルコンピューターの TCP 統計情報を取得します。

戻り値

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

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

戻り値 説明
ERROR_INVALID_PARAMETER
pStats パラメーターが NULL であるか、 GetTcpStatisticspStats パラメーターの指すメモリに書き込めません。
その他
返されたエラーのメッセージ文字列を取得するには、 FormatMessage 関数を使用してください。

解説(Remarks)

GetTcpStatistics 関数は、現在のコンピューターにおける IPv4 の TCP 統計情報を返します。Windows XP 以降では、GetTcpStatisticsEx を使用して、IPv4 または IPv6 の TCP 統計情報を取得できます。

次の例では、ローカルコンピューターの TCP 統計情報を取得し、返されたデータからいくつかの値を出力します。

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

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

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) 
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

/* Note: could also use malloc() and free() */

int main()
{
    PMIB_TCPSTATS pTCPStats;
    DWORD dwRetVal = 0;

    pTCPStats = (MIB_TCPSTATS*) MALLOC (sizeof(MIB_TCPSTATS));
    if (pTCPStats == NULL) {
        printf("Error allocating memory\n");
        return 1;
    }

    if ((dwRetVal = GetTcpStatistics(pTCPStats)) == NO_ERROR) {
      printf("\tActive Opens: %ld\n", pTCPStats->dwActiveOpens);
      printf("\tPassive Opens: %ld\n", pTCPStats->dwPassiveOpens);
      printf("\tSegments Recv: %ld\n", pTCPStats->dwInSegs);
      printf("\tSegments Xmit: %ld\n", pTCPStats->dwOutSegs);
      printf("\tTotal # Conxs: %ld\n", pTCPStats->dwNumConns);
    }
    else {
      printf("GetTcpStatistics failed with error: %ld\n", dwRetVal);
      
      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 );
    }

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

各言語での呼び出し定義

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

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

GetTcpStatistics = ctypes.windll.iphlpapi.GetTcpStatistics
GetTcpStatistics.restype = wintypes.DWORD
GetTcpStatistics.argtypes = [
    ctypes.c_void_p,  # Statistics : MIB_TCPSTATS_LH* out
]
require 'fiddle'
require 'fiddle/import'

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

var (
	iphlpapi = windows.NewLazySystemDLL("IPHLPAPI.dll")
	procGetTcpStatistics = iphlpapi.NewProc("GetTcpStatistics")
)

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

extern "iphlpapi" fn GetTcpStatistics(
    Statistics: [*c]MIB_TCPSTATS_LH // MIB_TCPSTATS_LH* out
) callconv(std.os.windows.WINAPI) u32;
proc GetTcpStatistics(
    Statistics: ptr MIB_TCPSTATS_LH  # MIB_TCPSTATS_LH* out
): uint32 {.importc: "GetTcpStatistics", stdcall, dynlib: "IPHLPAPI.dll".}
pragma(lib, "iphlpapi");
extern(Windows)
uint GetTcpStatistics(
    MIB_TCPSTATS_LH* Statistics   // MIB_TCPSTATS_LH* out
);
ccall((:GetTcpStatistics, "IPHLPAPI.dll"), stdcall, UInt32,
      (Ptr{MIB_TCPSTATS_LH},),
      Statistics)
# Statistics : MIB_TCPSTATS_LH* out -> Ptr{MIB_TCPSTATS_LH}
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
uint32_t GetTcpStatistics(
    void* Statistics);
]]
local iphlpapi = ffi.load("iphlpapi")
-- iphlpapi.GetTcpStatistics(Statistics)
-- Statistics : MIB_TCPSTATS_LH* out
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('IPHLPAPI.dll');
const GetTcpStatistics = lib.func('__stdcall', 'GetTcpStatistics', 'uint32_t', ['void *']);
// GetTcpStatistics(Statistics)
// Statistics : MIB_TCPSTATS_LH* out -> 'void *'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("IPHLPAPI.dll", {
  GetTcpStatistics: { parameters: ["pointer"], result: "u32" },
});
// lib.symbols.GetTcpStatistics(Statistics)
// Statistics : MIB_TCPSTATS_LH* out -> "pointer"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
uint32_t GetTcpStatistics(
    void* Statistics);
C, "IPHLPAPI.dll");
// $ffi->GetTcpStatistics(Statistics);
// Statistics : MIB_TCPSTATS_LH* out
// 構造体/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 GetTcpStatistics(
        Pointer Statistics   // MIB_TCPSTATS_LH* out
    );
}
@[Link("iphlpapi")]
lib LibIPHLPAPI
  fun GetTcpStatistics = GetTcpStatistics(
    Statistics : MIB_TCPSTATS_LH*   # MIB_TCPSTATS_LH* out
  ) : UInt32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

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

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

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

(cffi:defcfun ("GetTcpStatistics" get-tcp-statistics :convention :stdcall) :uint32
  (statistics :pointer))   ; MIB_TCPSTATS_LH* out
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $GetTcpStatistics = Win32::API::More->new('IPHLPAPI',
    'DWORD GetTcpStatistics(LPVOID Statistics)');
# my $ret = $GetTcpStatistics->Call($Statistics);
# Statistics : MIB_TCPSTATS_LH* out -> LPVOID
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

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