GetHostName function
Namespace: Winsock2.h
Header: Winsock2.h
Library: Ws2_32.lib
Syntax
int WSAAPI gethostname(
char *name,
int namelen
);
Parameters
name | Type | Description |
---|---|---|
name | char * | Pointer to a buffer that receives the hostname. |
namelen | int | Length 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
- The hostname returned by
gethostname
is the local computer name as registered in the network. - For IPv6 or name resolution beyond the local host, use
GetAddrInfo
orgetaddrinfo
. - Initialize Winsock with
WSAStartup
before calling this function.
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;
}