Win32 API 日本語リファレンス
ホームNetworking.WinSock › gethostbyaddr

gethostbyaddr

関数
IPアドレスから対応するホスト情報を取得する。
DLLWS2_32.dll呼出規約winapiSetLastErrorあり対応OSWindows 8.1 以降

シグネチャ

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

HOSTENT* gethostbyaddr(
    LPCSTR addr,
    INT len,
    INT type
);

パラメーター

名前方向説明
addrLPCSTRinホストを検索する対象のネットワークアドレスを格納したバッファへのポインタ。
lenINTinaddrのサイズ(バイト)。
typeINTinアドレスファミリ(AF_INET等)を示す値。

戻り値の型: HOSTENT*

公式ドキュメント

gethostbyaddr マクロ関数 (wsipv6ok.h) は、ネットワークアドレスに対応するホスト情報を取得します。

解説(Remarks)

gethostbyaddr 関数は、指定されたネットワークアドレスに対応する名前とアドレスを格納した hostent 構造体へのポインターを返します。

gethostbyaddr 関数が返す hostent 構造体用のメモリは、Winsock DLL によってスレッドローカルストレージから内部的に割り当てられます。gethostbyaddr 関数または gethostbyname 関数をスレッド上で何回呼び出しても、割り当てて使用される hostent 構造体は 1 つだけです。同じスレッド上で gethostbyaddr または gethostbyname 関数をさらに呼び出す場合は、返された hostent 構造体をアプリケーションのバッファーにコピーする必要があります。そうしないと、同じスレッド上で以降に行われる gethostbyaddr または gethostbyname の呼び出しによって戻り値が上書きされます。返された hostent 構造体用に内部的に割り当てられたメモリは、スレッドの終了時に Winsock DLL によって解放されます。

アプリケーションは、返された hostent 構造体が使用するメモリを解放しようとしてはなりません。アプリケーションは、この構造体を変更したり、その構成要素を解放したりしてはなりません。さらに、この構造体はスレッドごとに 1 つのコピーしか割り当てられないため、アプリケーションは gethostbyaddr または gethostbyname への他の関数呼び出しを発行する前に、必要な情報をコピーしておく必要があります。

gethostbyaddr は Windows Sockets 2 以降では使用が推奨されておらず、getnameinfo 関数を使用すべきですが、 gethostbyaddr は NetBIOS 名を返すことができます。一方、 getnameinfo は返せません。NetBIOS 名前解決を必要とする開発者は、アプリケーションが NetBIOS 名から完全に独立するまで gethostbyaddr を使用する必要がある場合があります。

注意 gethostbyaddr 関数を使用した逆引き参照を行う機能は便利ですが、このような参照は本質的に信頼性が低いものとみなされており、ヒントとしてのみ使用すべきです。

サンプルコード

次の例は、gethostbyaddr 関数の使用方法を示しています。
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

int main(int argc, char **argv)
{

    //-----------------------------------------
    // Declare and initialize variables
    WSADATA wsaData;
    int iResult;

    DWORD dwError;
    int i = 0;
    int bIpv6 = 0;

    struct hostent *remoteHost;
    char *host_addr;
    struct in_addr addr = { 0 };
    IN6_ADDR addr6;

    char **pAlias;

    // Validate the parameters
    if (argc < 2) {
        printf("usage: %s 4 ipv4address\n", argv[0]);
        printf(" or\n");
        printf("usage: %s 6 ipv6address\n", argv[0]);
        printf("  to return the hostname\n");
        printf("       %s 4 127.0.0.1\n", argv[0]);
        printf("       %s 6 0::1\n", argv[0]);
        return 1;
    }
    // Validate parameters 
    if (atoi(argv[1]) == 4)
        bIpv6 = 0;
    else if (atoi(argv[1]) == 6)
        bIpv6 = 1;
    else {
        printf("usage: %s 4 ipv4address\n", argv[0]);
        printf(" or\n");
        printf("usage: %s 6 ipv6address\n", argv[0]);
        printf("  to return the hostname\n");
        printf("       %s 4 127.0.0.1\n", argv[0]);
        printf("       %s 6 0::1\n", argv[0]);
        return 1;
    }

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    host_addr = argv[2];

    printf("Calling gethostbyaddr with %s\n", host_addr);
    if (bIpv6 == 1) {
        {
            iResult = inet_pton(AF_INET6, host_addr, &addr6);
            if (iResult == 0) {
                printf("The IPv6 address entered must be a legal address\n");
                return 1;
            } else
                remoteHost = gethostbyaddr((char *) &addr6, 16, AF_INET6);
        }
    } else {
        addr.s_addr = inet_addr(host_addr);
        if (addr.s_addr == INADDR_NONE) {
            printf("The IPv4 address entered must be a legal address\n");
            return 1;
        } else
            remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
    }

    if (remoteHost == NULL) {
        dwError = WSAGetLastError();
        if (dwError != 0) {
            if (dwError == WSAHOST_NOT_FOUND) {
                printf("Host not found\n");
                return 1;
            } else if (dwError == WSANO_DATA) {
                printf("No data record found\n");
                return 1;
            } else {
                printf("Function failed with error: %ld\n", dwError);
                return 1;
            }
        }
    } else {
        printf("Function returned:\n");
        printf("\tOfficial name: %s\n", remoteHost->h_name);
        for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
            printf("\tAlternate name #%d: %s\n", ++i, *pAlias);
        }
        printf("\tAddress type: ");
        switch (remoteHost->h_addrtype) {
        case AF_INET:
            printf("AF_INET\n");
            break;
        case AF_INET6:
            printf("AF_INET6\n");
            break;
        case AF_NETBIOS:
            printf("AF_NETBIOS\n");
            break;
        default:
            printf(" %d\n", remoteHost->h_addrtype);
            break;
        }
        printf("\tAddress length: %d\n", remoteHost->h_length);

        if (remoteHost->h_addrtype == AF_INET) {
            while (remoteHost->h_addr_list[i] != 0) {
                addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
                printf("\tIPv4 Address #%d: %s\n", i, inet_ntoa(addr));
            }
        } else if (remoteHost->h_addrtype == AF_INET6)
            printf("\tRemotehost is an IPv6 address\n");
    }

    return 0;
}

Windows Phone 8: この関数は、Windows Phone 8 以降の Windows Phone ストアアプリでサポートされています。

Windows 8.1 および Windows Server 2012 R2: この関数は、Windows 8.1、Windows Server 2012 R2 以降の Windows ストアアプリでサポートされています。

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

各言語での呼び出し定義

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

HOSTENT* gethostbyaddr(
    LPCSTR addr,
    INT len,
    INT type
);
[DllImport("WS2_32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr gethostbyaddr(
    [MarshalAs(UnmanagedType.LPStr)] string addr,   // LPCSTR
    int len,   // INT
    int type   // INT
);
<DllImport("WS2_32.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function gethostbyaddr(
    <MarshalAs(UnmanagedType.LPStr)> addr As String,   ' LPCSTR
    len As Integer,   ' INT
    type As Integer   ' INT
) As IntPtr
End Function
' addr : LPCSTR
' len : INT
' type : INT
Declare PtrSafe Function gethostbyaddr Lib "ws2_32" ( _
    ByVal addr As String, _
    ByVal len As Long, _
    ByVal type As Long) As LongPtr
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

gethostbyaddr = ctypes.windll.ws2_32.gethostbyaddr
gethostbyaddr.restype = ctypes.c_void_p
gethostbyaddr.argtypes = [
    wintypes.LPCSTR,  # addr : LPCSTR
    ctypes.c_int,  # len : INT
    ctypes.c_int,  # type : INT
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('WS2_32.dll')
gethostbyaddr = Fiddle::Function.new(
  lib['gethostbyaddr'],
  [
    Fiddle::TYPE_VOIDP,  # addr : LPCSTR
    Fiddle::TYPE_INT,  # len : INT
    Fiddle::TYPE_INT,  # type : INT
  ],
  Fiddle::TYPE_VOIDP)
#[link(name = "ws2_32")]
extern "system" {
    fn gethostbyaddr(
        addr: *const u8,  // LPCSTR
        len: i32,  // INT
        type: i32  // INT
    ) -> *mut HOSTENT;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[DllImport("WS2_32.dll", SetLastError = true)]
public static extern IntPtr gethostbyaddr([MarshalAs(UnmanagedType.LPStr)] string addr, int len, int type);
"@
$api = Add-Type -MemberDefinition $sig -Name 'WS2_32_gethostbyaddr' -Namespace Win32 -PassThru
# $api::gethostbyaddr(addr, len, type)
#uselib "WS2_32.dll"
#func global gethostbyaddr "gethostbyaddr" sptr, sptr, sptr
; gethostbyaddr addr, len, type   ; 戻り値は stat
; addr : LPCSTR -> "sptr"
; len : INT -> "sptr"
; type : INT -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
#uselib "WS2_32.dll"
#cfunc global gethostbyaddr "gethostbyaddr" str, int, int
; res = gethostbyaddr(addr, len, type)
; addr : LPCSTR -> "str"
; len : INT -> "int"
; type : INT -> "int"
; HOSTENT* gethostbyaddr(LPCSTR addr, INT len, INT type)
#uselib "WS2_32.dll"
#cfunc global gethostbyaddr "gethostbyaddr" str, int, int
; res = gethostbyaddr(addr, len, type)
; addr : LPCSTR -> "str"
; len : INT -> "int"
; type : INT -> "int"
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	ws2_32 = windows.NewLazySystemDLL("WS2_32.dll")
	procgethostbyaddr = ws2_32.NewProc("gethostbyaddr")
)

// addr (LPCSTR), len (INT), type (INT)
r1, _, err := procgethostbyaddr.Call(
	uintptr(unsafe.Pointer(windows.BytePtrFromString(addr))),
	uintptr(len),
	uintptr(type),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // HOSTENT*
function gethostbyaddr(
  addr: PAnsiChar;   // LPCSTR
  len: Integer;   // INT
  type: Integer   // INT
): Pointer; stdcall;
  external 'WS2_32.dll' name 'gethostbyaddr';
result := DllCall("WS2_32\gethostbyaddr"
    , "AStr", addr   ; LPCSTR
    , "Int", len   ; INT
    , "Int", type   ; INT
    , "Ptr")   ; return: HOSTENT*
●gethostbyaddr(addr, len, type) = DLL("WS2_32.dll", "void* gethostbyaddr(char*, int, int)")
# 呼び出し: gethostbyaddr(addr, len, type)
# addr : LPCSTR -> "char*"
# len : INT -> "int"
# type : INT -> "int"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

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

typedef gethostbyaddrNative = Pointer<Void> Function(Pointer<Utf8>, Int32, Int32);
typedef gethostbyaddrDart = Pointer<Void> Function(Pointer<Utf8>, int, int);
final gethostbyaddr = DynamicLibrary.open('WS2_32.dll')
    .lookupFunction<gethostbyaddrNative, gethostbyaddrDart>('gethostbyaddr');
// addr : LPCSTR -> Pointer<Utf8>
// len : INT -> Int32
// type : INT -> Int32
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function gethostbyaddr(
  addr: PAnsiChar;   // LPCSTR
  len: Integer;   // INT
  type: Integer   // INT
): Pointer; stdcall;
  external 'WS2_32.dll' name 'gethostbyaddr';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "gethostbyaddr"
  c_gethostbyaddr :: CString -> Int32 -> Int32 -> IO (Ptr ())
-- addr : LPCSTR -> CString
-- len : INT -> Int32
-- type : INT -> Int32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let gethostbyaddr =
  foreign "gethostbyaddr"
    (string @-> int32_t @-> int32_t @-> returning (ptr void))
(* addr : LPCSTR -> string *)
(* len : INT -> int32_t *)
(* type : INT -> int32_t *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library ws2_32 (t "WS2_32.dll"))
(cffi:use-foreign-library ws2_32)

(cffi:defcfun ("gethostbyaddr" gethostbyaddr :convention :stdcall) :pointer
  (addr :string)   ; LPCSTR
  (len :int32)   ; INT
  (type :int32))   ; INT
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $gethostbyaddr = Win32::API::More->new('WS2_32',
    'LPVOID gethostbyaddr(LPCSTR addr, int len, int type)');
# my $ret = $gethostbyaddr->Call($addr, $len, $type);
# addr : LPCSTR -> LPCSTR
# len : INT -> int
# type : INT -> int
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

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