Home

GetHostName function

Namespace: Winsock2.h

Header: Winsock2.h

Library: Ws2_32.lib

Syntax

int WSAAPI gethostname(
    char *name,
    int   namelen
);

Parameters

nameTypeDescription
namechar *Pointer to a buffer that receives the hostname.
namelenintLength of the buffer, in bytes.

Return value

Returns 0 on success. On error, returns SOCKET_ERROR and sets WSAGetLastError() to indicate the error code.

Remarks

Example

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")

int main(void) {
    WSADATA wsaData;
    char hostname[256];
    int result;

    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        printf("WSAStartup failed.\n");
        return 1;
    }

    result = gethostname(hostname, sizeof(hostname));
    if (result == SOCKET_ERROR) {
        printf("gethostname failed with error: %d\n", WSAGetLastError());
    } else {
        printf("Local host name: %s\n", hostname);
    }

    WSACleanup();
    return 0;
}

See also