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

gethostname

関数
ローカルコンピューターの標準ホスト名を取得する。
DLLWS2_32.dll呼出規約winapiSetLastErrorあり対応OSWindows 8.1 以降

シグネチャ

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

INT gethostname(
    LPSTR name,
    INT namelen
);

パラメーター

名前方向説明
nameLPSTRoutローカルホスト名を受け取るバッファーへのポインター。
namelenINTinname パラメーターが指すバッファーの長さ (バイト単位)。

戻り値の型: INT

公式ドキュメント

gethostname 関数 (winsock.h) は、ローカルコンピューターの標準ホスト名を取得します。

戻り値

エラーが発生しない場合、 gethostname はゼロを返します。それ以外の場合は SOCKET_ERROR を返し、 WSAGetLastError を呼び出すことで特定のエラーコードを取得できます。

エラーコード 意味
WSAEFAULT
name パラメーターが NULL ポインターであるか、ユーザーアドレス空間の有効な一部ではありません。このエラーは、namelen パラメーターで指定されたバッファーサイズが、完全なホスト名を保持するには小さすぎる場合にも返されます。
WSANOTINITIALISED
この関数を使用する前に、 WSAStartup の呼び出しが成功している必要があります。
WSAENETDOWN
ネットワークサブシステムで障害が発生しました。
WSAEINPROGRESS
ブロッキング型の Windows Sockets 1.1 呼び出しが進行中であるか、サービスプロバイダーがコールバック関数をまだ処理中です。

解説(Remarks)

gethostname 関数は、name パラメーターで指定されたバッファーにローカルホストの名前を返します。ホスト名は null 終端文字列として返されます。ホスト名の形式は Windows Sockets プロバイダーに依存します。単純なホスト名の場合もあれば、完全修飾ドメイン名 (FQDN) の場合もあります。ただし、返される名前は gethostbyname および WSAAsyncGetHostByName で正常に解析できることが保証されています。

name パラメーターが指すバッファーに返される名前の最大長は、名前空間プロバイダーに依存します。

gethostname 関数を Windows Server 2008、Windows Server 2003、または Windows 2000 Server のクラスターリソース上で使用し、かつ CLUSTER_NETWORK_NAME 環境変数が定義されている場合、この環境変数の値が実際のホスト名よりも優先され、その値が返されます。クラスターリソース上では、CLUSTER_NETWORK_NAME 環境変数にクラスターの名前が含まれます。

gethostname 関数は、Svgguid.h ヘッダーファイルで定義されている SVCID_HOSTNAME GUID を使用して、名前空間プロバイダーに照会し、ローカルホスト名を判定します。応答する名前空間プロバイダーがない場合、 gethostname 関数はローカルコンピューターの NetBIOS 名を返します。

name パラメーターが指すバッファーに返される文字列の最大長 (バイト単位) は名前空間プロバイダーに依存しますが、この文字列は 256 バイト以下である必要があります。したがって、256 バイトのバッファーを name パラメーターに渡し、namelen パラメーターを 256 に設定すれば、バッファーサイズは常に十分です。

注意 ローカルホスト名が構成されていない場合でも、 gethostname は成功し、 gethostbyname または WSAAsyncGetHostByName が解決できるトークンホスト名を返す必要があります。

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>

INT gethostname(
    LPSTR name,
    INT namelen
);
[DllImport("WS2_32.dll", SetLastError = true, ExactSpelling = true)]
static extern int gethostname(
    [MarshalAs(UnmanagedType.LPStr)] System.Text.StringBuilder name,   // LPSTR out
    int namelen   // INT
);
<DllImport("WS2_32.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function gethostname(
    <MarshalAs(UnmanagedType.LPStr)> name As System.Text.StringBuilder,   ' LPSTR out
    namelen As Integer   ' INT
) As Integer
End Function
' name : LPSTR out
' namelen : INT
Declare PtrSafe Function gethostname Lib "ws2_32" ( _
    ByVal name As String, _
    ByVal namelen As Long) As Long
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

gethostname = ctypes.windll.ws2_32.gethostname
gethostname.restype = ctypes.c_int
gethostname.argtypes = [
    wintypes.LPSTR,  # name : LPSTR out
    ctypes.c_int,  # namelen : INT
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

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

var (
	ws2_32 = windows.NewLazySystemDLL("WS2_32.dll")
	procgethostname = ws2_32.NewProc("gethostname")
)

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

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

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

foreign import stdcall safe "gethostname"
  c_gethostname :: CString -> Int32 -> IO Int32
-- name : LPSTR out -> CString
-- namelen : INT -> Int32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let gethostname =
  foreign "gethostname"
    (string @-> int32_t @-> returning int32_t)
(* name : LPSTR out -> string *)
(* namelen : 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 ("gethostname" gethostname :convention :stdcall) :int32
  (name :pointer)   ; LPSTR out
  (namelen :int32))   ; INT
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $gethostname = Win32::API::More->new('WS2_32',
    'int gethostname(LPSTR name, int namelen)');
# my $ret = $gethostname->Call($name, $namelen);
# name : LPSTR out -> LPSTR
# namelen : INT -> int
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

公式の関連項目