Hostname
From Rosetta Code
You are encouraged to solve this task according to the task description, using any language you may know.
Find the name of the host on which the routine is running.
[edit] Ada
Works with GCC/GNAT
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Sockets;
procedure Demo is
begin
Put_Line (GNAT.Sockets.Host_Name);
end Demo;
[edit] ALGOL 68
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: POSIX version .1
STRING hostname;
get(read OF execve child pipe("/bin/hostname","hostname",""), hostname);
print(("hostname: ", hostname, new line))
[edit] Aikido
println (System.hostname)
[edit] AutoHotkey
MsgBox % A_ComputerName
[edit] AWK
$ awk 'BEGIN{print ENVIRON["HOST"]}'
E51A08ZD
[edit] C/C++
Works with: gcc version 4.0.1
Works with: POSIX version .1
#include <limits.h>
#include <unistd.h>
int main()
{
char name[_POSIX_HOST_NAME_MAX+1];
gethostname(name, _POSIX_HOST_NAME_MAX+1);
return 0;
}
[edit] C#
System.Net.Dns.GetHostName();
[edit] Clojure
(.. java.net.InetAddress getLocalHost getHostName)
java -cp clojure.jar clojure.main -e "(.. java.net.InetAddress getLocalHost getHostName)"
[edit] Common Lisp
Another operating system feature that is implemented differently across lisp implementations. Here we show how to create a function that obtains the required result portably by working differently for each supported implementation. This technique is heavily used to make portable lisp libraries.
(defun get-host-name ()
#+sbcl (machine-instance)
#+clisp (let ((s (machine-instance))) (subseq s 0 (position #\Space s)))
#-(or sbcl clisp) (error "get-host-name not implemented"))
Library: CFFI
Another way is to use the FFI to access POSIX' gethostname(2):
(cffi:defcfun ("gethostname" c-gethostname) :int
(buf :pointer) (len :unsigned-long))
(defun get-hostname ()
(cffi:with-foreign-object (buf :char 256)
(unless (zerop (c-gethostname buf 256))
(error "Can't get hostname"))
(values (cffi:foreign-string-to-lisp buf))))
BOA> (get-hostname)
"aurora"
[edit] D
import std.stdio;
import std.socket;
void main()
{
writefln("%s", Socket.hostName());
}
[edit] E
makeCommand("hostname")()[0].trim()
Not exactly a good way to do it. A better way ought to be introduced along with a proper socket interface.
[edit] Factor
host-name
[edit] Forth
Works with: GNU Forth version 0.7.0
include unix/socket.fs
hostname type
[edit] Fortran
Works with: gfortran
The function/subroutine HOSTNM is a GNU extension.
program HostTest
character(len=128) :: name
call hostnm(name)
print *, name
end program HostTest
[edit] Go
package main
import (
"fmt"
"os"
)
func main() {
host, _ := os.Hostname()
fmt.Printf("hostname: %s\n", host)
}
[edit] Groovy
println InetAddress.localHost.hostName
[edit] Haskell
Library: network
import Network.BSD
main = do hostName <- getHostName
putStrLn hostName
[edit] Icon and Unicon
[edit] Icon
procedure main()
write(&host)
end
[edit] Unicon
This Icon solution works in Unicon.
[edit] IDL
hostname = GETENV('computername')
[edit] J
NB. Load the socket libraries
load 'socket'
coinsert 'jsocket'
NB. fetch and implicitly display the hostname
> {: sdgethostname ''
NB. If fetching the hostname is the only reason for loading the socket libraries,
NB. and the hostname is fetched only once, then use a 'one-liner' to accomplish it:
> {: sdgethostname coinsert 'jsocket' [ load 'socket'
[edit] Java
import java.net.*;
class DiscoverHostName {
public static void main(String[] args) {
try {
String hostName = InetAddress.getLocalHost().getHostName();
System.out.println(hostName);
} catch (UnknownHostException e) { // Doesn't actually happen, but Java requires it be handled.
}
}
}
[edit] JavaScript
Works with: JScript
var network = new ActiveXObject('WScript.Network');
var hostname = network.computerName;
WScript.echo(hostname);
[edit] Liberty BASIC
lpBuffer$=Space$(128) + Chr$(0)
struct SIZE,sz As Long
SIZE.sz.struct=Len(lpBuffer$)
calldll #kernel32, "GetComputerNameA",lpBuffer$ as ptr, SIZE as struct, result as Long
nSize=SIZE.sz.struct
CurrentComputerName$=Trim$(Left$(lpBuffer$, SIZE.sz.struct))
print CurrentComputerName$
[edit] Mathematica
$MachineName
[edit] MATLAB
This is a built-in MATLAB function. "failed" is a Boolean which will be false if the command sent to the OS succeeds. "hostname" is a string containing the system's hostname, provided that the external command hostname exists.
[failed,hostname] = system('hostname')
[edit] Modula-3
MODULE Hostname EXPORTS Main;
IMPORT IO, OSConfig;
BEGIN
IO.Put(OSConfig.HostName() & "\n");
END Hostname.
[edit] MUMPS
The output varies by implementation. The following is an example of Intersystem's Caché 5.2.0.329.0:
Write $System
USER>Write $SYSTEM STORMSTATION:CACHE520
The portion before the colon is the machine running Caché, and the portion after the colon is the instance.
[edit] Objective-C
NSLog(@"%@", [[NSHost currentHost] name]);
(does not work on iPhone)
[edit] Objeck
use Net;
bundle Default {
class Hello {
function : Main(args : String[]) ~ Nil {
TCPSocket->HostName()->PrintLine();
}
}
}
[edit] OCaml
Unix.gethostname()
[edit] Octave
Similarly to MATLAB, we could call system command hostname to know the hostname. But we can also call the internal function uname() which returns a structure holding several informations, among these the hostname (nodename):
uname().nodename
[edit] Oz
{System.showInfo {OS.getHostByName 'localhost'}.name}
[edit] Perl
Works with: Perl version 5.8.6
Library: Sys::HostnameHostname
use Sys::Hostname;
$name = hostname;
[edit] PHP
echo $_SERVER['HTTP_HOST'];
echo php_uname('n');
Works with: PHP version 5.3+
echo gethostname();
[edit] PicoLisp
This will just print the hostname:
(call 'hostname)
To use it as a string in a program:
(in '(hostname) (line T))
[edit] Pike
import System;
int main(){
write(gethostname() + "\n");
}
[edit] PL/SQL
SET serveroutput ON
BEGIN
DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);
END;
[edit] Pop11
lvars host = sys_host_name();
[edit] PowerBASIC
This retreives the localhost's name:
HOST NAME TO hostname$
This attempts to retreive the name of an arbitrary machine on the network (assuming ipAddress& is valid):
HOST NAME ipAddress& TO hostname$
[edit] PowerShell
Windows systems have the ComputerName environment variable which can be used:
$Env:COMPUTERNAME
Also PowerShell can use .NET classes and methods:
[Net.Dns]::GetHostName()
[edit] PureBasic
Works with: PureBasic version 4.41
InitNetwork()
answer$=Hostname()
[edit] Python
Works with: Python version 2.5
import socket
host = socket.gethostname()
[edit] R
Sys.info provides information about the platform that R is running on. The following code returns the hostname as a string.
Sys.info()[["nodename"]]
Note that Sys.info isn't guaranteed to be available on all platforms. As an alternative, you can call an OS command.
system("hostname", intern = TRUE)
... or retrieve an environment variable
env_var <- ifelse(.Platform$OS.type == "windows", "COMPUTERNAME", "HOSTNAME")
Sys.getenv(env_var)
[edit] REBOL
print system/network/host
[edit] Ruby
require 'socket'
host = Socket.gethostname
[edit] Scala
println(java.net.InetAddress.getLocalHost.getHostName)
[edit] Scheme
Works with: Chicken Scheme
(use posix)
(get-host-name)
[edit] Slate
Platform current nodeName
[edit] SNOBOL4
output = host(4,"HOSTNAME")
end
[edit] Standard ML
NetHostDB.getHostName ()
[edit] Tcl
The basic introspection tool in TCL is the info command. It can be used to find out about the version of the current Tcl or Tk, the available commands and libraries, variables, functions, the level of recursive interpreter invocation, and, amongst a myriad other things, the name of the current machine:
set hname [info hostname]
[edit] Toka
2 import gethostname
1024 chars is-array foo
foo 1024 gethostname
foo type
[edit] UNIX Shell
hostname
or
uname -n
[edit] Ursala
The user-defined hostname function ignores its argument and returns a string.
#import cli
hostname = ~&hmh+ (ask bash)/<>+ <'hostname'>!
For example, the following function returns the square root of its argument if it's running on host kremvax, but otherwise returns the square.
#import flo
creative_accounting = (hostname== 'kremvax')?(sqrt,sqr)

