| < Day Day Up > |
|
The gethostname function is a miscellaneous function that permits the application to identify the name of the host on which it executes. The function prototype for gethostname is defined as:
#include <unistd.h> int gethostname( char *name, size_t len );
The caller provides a preallocated buffer pointer (of at least size 255) that the gethostname function uses to store the host name. The size of the buffer is provided as the len argument. Sample usage of the gethostname function is illustrated in Listing 4.6.
Listing 4.6 Sample usage of the gethostname function.
#define MAX_HOSTNAME 255 char hostbuffer[MAX_HOSTNAME+1] int ret; ret = gethostname( hostbuffer, MAX_HOSTNAME ); if (ret == 0) { printf( "Host name is %s\n", hostbuffer ); }
The result of gethostname is a NULL-terminated string representing the name of the host. The host name is commonly truncated if the application provides a buffer of insufficient size.
The application can also set the name of the current host using the sethostname function:
#include <unistd.h> int sethostname( const char *name, size_t len );
A simple example of sethostname is shown in Listing 4.7.
Listing 4.7 Sample usage of the sethostname function.
#define MAX_HOSTNAME 255 char hostbuffer[MAX_HOSTNAME+1] int ret; strcpy( hostbuffer, "Elise" ); ret = sethostname( hostbuffer, strlen(hostbuffer) ); if (ret == 0) { printf( "Host name is now %s\n", hostbuffer ); }
Both gethostname and sethostname return 0 on success and –1 if an error occurs.
| < Day Day Up > |
|