8.5. gethostname()

Returns the name of the system


#include <sys/unistd.h>

int gethostname(char *name, size_t len);


Your system has a name. They all do. This is a slightly more Unixy thing than the rest of the networky stuff we've been talking about, but it still has its uses.

For instance, you can get your host name, and then call gethostbyname() to find out your IP address.

The parameter name should point to a buffer that will hold the host name, and len is the size of that buffer in bytes. gethostname() won't overwrite the end of the buffer (it might return an error, or it might just stop writing), and it will NUL-terminate the string if there's room for it in the buffer.

Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly.)


char hostname[128];

gethostname(hostname, sizeof(hostname));
printf("My hostname: %s\n", hostname);

See Also