Skip to content

Core\Os::hostname

Core\Os::hostname(): string

Returns the name of the machine your program runs on.

The name is the one the machine has for itself. Reading it does not use the network, so it is quick and works on a machine with no network at all.

Use it when many servers do the same work and you need to know which one did something. Put it at the start of a log line, or in the name of a worker that takes jobs from a queue. The name is different on every machine, so do not write it into a test.

The examples show how to read the name, how to add it to a log line, and how to give each worker a name that no other worker has.

Return value

Returns string. The machine's name.

Errors

  • RuntimeErrorThe operating system did not return a name, or the name is not valid UTF-8.

Examples

The machine name

<?nvs
// Shows how to read the name of the machine your program runs on.
string $host = Core\Os::hostname();
// The name is different on every machine, so this example only checks it.
// A machine always has a name, so this prints `yes`.
echo Core\Str::length($host) > 0 ? 'yes' : 'no', "\n";
Output
yes

A log line that names the machine

<?nvs
// Shows how to start each log line with the machine's name. When many servers
// write to one log, the name tells you which server wrote a line.
string $host = Core\Os::hostname();
string $line = '[' . $host . '] order 1042 saved';
// The line starts with the name, so the message comes after it. This prints `yes`.
echo Core\Str::endsWith($line, '] order 1042 saved') ? 'yes' : 'no', "\n";
Output
yes

A name for each worker

<?nvs
// Shows how to give a worker a name that no other worker has. A job queue uses
// this name to record which worker took a job.
// Two workers on one machine have different process numbers. Two machines have
// different names. So the name and the number together are never the same twice.
string $worker = Core\Os::hostname() . '-' . Core\Os::pid();
// The name ends with this program's process number. This prints `yes`.
echo Core\Str::endsWith($worker, '-' . Core\Os::pid()) ? 'yes' : 'no', "\n";
Output
yes