gethostnamesethostname Functions

 < Day Day Up > 



gethostname/sethostname Functions

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.

start example
#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 ); }
end example

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.

start example
#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 ); }
end example

Both gethostname and sethostname return 0 on success and –1 if an error occurs.



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net