Hostname
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.
Ada
Works with GCC/GNAT <lang ada>with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets;
procedure Demo is begin
Put_Line (GNAT.Sockets.Host_Name);
end Demo;</lang>
ALGOL 68
<lang algol68>STRING hostname; get(read OF execve child pipe("/bin/hostname","hostname",""), hostname); print(("hostname: ", hostname, new line))</lang>
Aikido
<lang aikido> println (System.hostname) </lang>
AutoHotkey
<lang AutoHotkey>MsgBox % A_ComputerName</lang>
AWK
<lang awk>$ awk 'BEGIN{print ENVIRON["HOST"]}' E51A08ZD</lang>
C
<lang c>#include <limits.h>
- include <unistd.h>
int main() {
char name[_POSIX_HOST_NAME_MAX+1]; gethostname(name, _POSIX_HOST_NAME_MAX+1); return 0;
}</lang>
C#
<lang csharp>System.Net.Dns.GetHostName();</lang>
Clojure
<lang clojure> (.. java.net.InetAddress getLocalHost getHostName) </lang>
<lang shell> java -cp clojure.jar clojure.main -e "(.. java.net.InetAddress getLocalHost getHostName)" </lang>
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. <lang lisp>(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"))</lang>
Another way is to use the FFI to access POSIX' gethostname(2)
:
<lang lisp>(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))))</lang>
<lang lisp>BOA> (get-hostname) "aurora"</lang>
D
<lang d>import std.stdio; import std.socket;
void main() {
writefln("%s", Socket.hostName());
}</lang>
E
<lang e>makeCommand("hostname")()[0].trim()</lang>
Not exactly a good way to do it. A better way ought to be introduced along with a proper socket interface.
Factor
<lang factor>host-name</lang>
Forth
<lang forth>include unix/socket.fs
hostname type</lang>
Fortran
The function/subroutine HOSTNM is a GNU extension. <lang fortran>program HostTest
character(len=128) :: name call hostnm(name) print *, name
end program HostTest</lang>
Go
<lang Go>package main
import ( "fmt" "os" )
func main() { host, _ := os.Hostname() fmt.Printf("hostname: %s\n", host) }</lang>
Groovy
<lang groovy>println InetAddress.localHost.hostName</lang>
Haskell
<lang haskell>import Network.BSD main = do hostName <- getHostName
putStrLn hostName</lang>
Icon and Unicon
Icon
<lang icon>procedure main()
write(&host)
end</lang>
Unicon
This Icon solution works in Unicon.
IDL
<lang idl>hostname = GETENV('computername')</lang>
J
<lang 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'</lang>
Java
<lang 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. } }
}</lang>
JavaScript
<lang javascript>var network = new ActiveXObject('WScript.Network'); var hostname = network.computerName; WScript.echo(hostname);</lang>
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.
<lang Matlab>[failed,hostname] = system('hostname')</lang>
Modula-3
<lang modula3>MODULE Hostname EXPORTS Main;
IMPORT IO, OSConfig;
BEGIN
IO.Put(OSConfig.HostName() & "\n");
END Hostname.</lang>
Objective-C
<lang objc>NSLog(@"%@", [[NSHost currentHost] name]);</lang> (does not work on iPhone)
OCaml
<lang ocaml>Unix.gethostname()</lang>
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):
<lang octave>uname().nodename</lang>
Oz
<lang oz>{System.showInfo {OS.getHostByName 'localhost'}.name}</lang>
Perl
<lang perl>use Sys::Hostname;
$name = hostname;</lang>
PHP
<lang php>echo $_SERVER['HTTP_HOST'];</lang>
<lang php>echo php_uname('n');</lang>
<lang php>echo gethostname();</lang>
PicoLisp
This will just print the hostname: <lang PicoLisp>(call 'hostname)</lang> To use it as a stringin a program: <lang PicoLisp>(in '(hostname) (line T))</lang>
Pike
<lang pike>import System;
int main(){
write(gethostname() + "\n");
}</lang>
PL/SQL
<lang plsql>SET serveroutput on BEGIN
DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);
END;</lang>
Pop11
<lang pop11>lvars host = sys_host_name();</lang>
PowerBASIC
This retreives the localhost's name:
<lang powerbasic>HOST NAME TO hostname$</lang>
This attempts to retreive the name of an arbitrary machine on the network (assuming ipAddress& is valid):
<lang powerbasic>HOST NAME ipAddress& TO hostname$</lang>
PowerShell
Windows systems have the ComputerName
environment variable which can be used:
<lang powershell>$Env:COMPUTERNAME</lang>
Also PowerShell can use .NET classes and methods:
<lang powershell>[Net.Dns]::GetHostName()</lang>
PureBasic
<lang PureBasic>InitNetwork() answer$=Hostname()</lang>
Python
<lang python>import socket host = socket.gethostname()</lang>
R
Sys.info provides information about the platform that R is running on. The following code returns the hostname as a string. <lang R>Sys.info()"nodename"</lang> Note that Sys.info isn't guaranteed to be available on all platforms. As an alternative, you can call an OS command. <lang R>system("hostname", intern = TRUE)</lang> ... or retrieve an environment variable <lang R> env_var <- ifelse(.Platform$OS.type == "windows", "COMPUTERNAME", "HOSTNAME") Sys.getenv(env_var) </lang>
REBOL
<lang REBOL>print system/network/host</lang>
Ruby
<lang ruby>require 'socket' host = Socket.gethostname</lang>
Scala
<lang scala>println(java.net.InetAddress.getLocalHost.getHostName)</lang>
Scheme
<lang scheme>(use posix) (get-host-name)</lang>
Slate
<lang slate>Platform current nodeName</lang>
SNOBOL4
<lang snobol4>
output = host(4,"HOSTNAME")
end</lang>
Standard ML
<lang sml>NetHostDB.getHostName ()</lang>
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:
<lang Tcl>set hname [info hostname]</lang>
Toka
<lang toka>2 import gethostname 1024 chars is-array foo foo 1024 gethostname foo type</lang>
UNIX Shell
<lang bash>hostname</lang> or <lang bash>uname -n</lang>
Ursala
The user-defined hostname function ignores its argument and returns a string. <lang Ursala>#import cli
hostname = ~&hmh+ (ask bash)/<>+ <'hostname'>!</lang> For example, the following function returns the square root of its argument if it's running on host kremvax, but otherwise returns the square. <lang Ursala>#import flo
creative_accounting = (hostname== 'kremvax')?(sqrt,sqr)</lang>
- Programming Tasks
- Programming environment operations
- Networking and Web Interaction
- Ada
- ALGOL 68
- Aikido
- AutoHotkey
- AWK
- C
- C sharp
- Clojure
- Common Lisp
- CFFI
- D
- E
- E examples needing attention
- Factor
- Forth
- Fortran
- Go
- Groovy
- Haskell
- Network
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- MATLAB
- Modula-3
- Objective-C
- OCaml
- Octave
- Oz
- Perl
- PHP
- PicoLisp
- Pike
- PL/SQL
- Pop11
- PowerBASIC
- PowerShell
- PureBasic
- Python
- R
- REBOL
- Ruby
- Scala
- Scheme
- Slate
- SNOBOL4
- Standard ML
- Tcl
- Toka
- UNIX Shell
- Ursala
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit