Go to the previous, next section.

Host Identification

This section explains how to identify the particular machine that your program is running on. The identification of a machine consists of its Internet host name and Internet address; see section The Internet Namespace.

Prototypes for these functions appear in `unistd.h'. The shell commands hostname and hostid work by calling them.

Function: int gethostname (char *name, size_t size)

This function returns the name of the host machine in the array name. The size argument specifies the size of this array, in bytes.

The return value is 0 on success and -1 on failure. In the GNU C library, gethostname fails if size is not large enough; then you can try again with a larger array. The following errno error condition is defined for this function:

ENAMETOOLONG
The size argument is less than the size of the host name plus one.

On some systems, there is a symbol for the maximum possible host name length: MAXHOSTNAMELEN. It is defined in `sys/param.h'. But you can't count on this to exist, so it is cleaner to handle failure and try again.

gethostname stores the beginning of the host name in name even if the host name won't entirely fit. For some purposes, a truncated host name is good enough. If it is, you can ignore the error code.

Function: int sethostname (const char *name, size_t length)

The sethostname function sets the name of the host machine to name, a string with length length. Only privileged processes are allowed to do this. Usually it happens just once, at system boot time.

The return value is 0 on success and -1 on failure. The following errno error condition is defined for this function:

EPERM
This process cannot set the host name because it is not privileged.

Function: long int gethostid (void)

This function returns the "host ID" of the machine the program is running on. By convention, this is usually the primary Internet address of that machine, converted to a long int. But on some systems it is a meaningless but unique number which is hard-coded for each machine.

Function: int sethostid (long int id)

The sethostid function sets the "host ID" of the host machine to id. Only privileged processes are allowed to do this. Usually it happens just once, at system boot time.

The return value is 0 on success and -1 on failure. The following errno error condition is defined for this function:

EPERM
This process cannot set the host name because it is not privileged.

ENOSYS
The operating system does not support setting the host ID. On some systems, the host ID is a meaningless but unique number hard-coded for each machine.

Go to the previous, next section.