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.
[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
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] BBC BASIC
INSTALL @lib$+"SOCKLIB"
PROC_initsockets
PRINT "hostname: " FN_gethostname
PROC_exitsockets
[edit] C/C++
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <unistd.h>
int main(void)
{
char name[_POSIX_HOST_NAME_MAX + 1];
return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
[edit] C#
System.Net.Dns.GetHostName();
[edit] Caché ObjectScript
Write ##class(%SYS.System).GetNodeName()
[edit] Clojure
(.. java.net.InetAddress getLocalHost getHostName)
java -cp clojure.jar clojure.main -e "(.. java.net.InetAddress getLocalHost getHostName)"
[edit] CoffeeScript
os = require 'os'
console.log os.hostname()
[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"))
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, std.socket;
void main() {
writeln(Socket.hostName());
}
[edit] Delphi
program ShowHostName;
{$APPTYPE CONSOLE}
uses Windows;
var
lHostName: array[0..255] of char;
lBufferSize: DWORD;
begin
lBufferSize := 256;
if GetComputerName(lHostName, lBufferSize) then
Writeln(lHostName)
else
Writeln('error getting host name');
end.
[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] F#
printfn "%s" (System.Net.Dns.GetHostName())
[edit] Factor
host-name
[edit] Forth
include unix/socket.fs
hostname type
[edit] Erlang
Host = net_adm:localhost().
[edit] friendly interactive shell
hostname
or
uname -n
[edit] Fortran
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
import Network.BSD
main = do hostName <- getHostName
putStrLn hostName
[edit] Icon and Unicon
procedure main()
write(&host)
end
[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(final String[] args) {
try {
System.out.println(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) { // Doesn't actually happen, but Java requires it be handled.
}
}
}
[edit] JavaScript
var network = new ActiveXObject('WScript.Network');
var hostname = network.computerName;
WScript.echo(hostname);
[edit] Lua
Requires: LuaSocket
socket = require "socket"
print( socket.dns.gethostname() )
[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
CurrentComputerName$=Trim$(Left$(lpBuffer$, SIZE.sz.struct))
print CurrentComputerName$
[edit] Maple
Sockets:-GetHostName()
[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] mIRC Scripting Language
echo -ag $host
[edit] Modula-3
MODULE Hostname EXPORTS Main;
IMPORT IO, OSConfig;
BEGIN
IO.Put(OSConfig.HostName() & "\n");
END Hostname.
[edit] MUMPS
Write $Piece($System,":")
[edit] NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols binary
say InetAddress.getLocalHost.getHostName
[edit] NewLISP
(! "hostname")
[edit] Objective-C
Cocoa / Cocoa Touch / GNUstep:
NSLog(@"%@", [[NSProcessInfo processInfo] hostName]);
Example Output:
2010-09-16 16:20:00.000 Playground[1319:a0f] sierra117.local // Hostname is sierra117.local.
[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] ooRexx
These solutions are platform specific.
[edit] Windows Platform
A solution using ActiveX/OLE on Windows
say .oleObject~new('WScript.Network')~computerName
and one using the Windows environment variables
say value('COMPUTERNAME',,'environment')
[edit] UNIX Platform
Some UNIX solutions (tested under Mac OS X):
ooRexx (and Rexx) can issue commands directly to the shell it's running under. Output of the shell commands will normally be STDOUT and STDERR. These next two samples will simply output the host name to the console if the program is run from a command prompt.
- Note: The address command clause causes the contents of the literal string that follows it to be sent to the command shell.
address command 'hostname -f'
address command "echo $HOSTNAME"
Command output can also be captured by the program to allow further processing. ooRexx provides an external data queue manager (rxqueue) that can be used for this. In the following examples output written to STDOUT/STDERR is piped into rxqueue which sends it in turn to a Rexx queue for further processing by the program:
/* Rexx */
address command "echo $HOSTNAME | rxqueue"
address command "hostname -f | rxqueue"
loop q_ = 1 while queued() > 0
parse pull hn
say q_~right(2)':' hn
end q_
A utility class is also provided as a wrapper around the external data queue:
/* Rexx */
qq = .rexxqueue~new()
address command "echo $HOSTNAME | rxqueue"
address command "hostname -f | rxqueue"
loop q_ = 1 while qq~queued() > 0
hn = qq~pull()
say q_~right(2)':' hn
end q_
[edit] Oz
{System.showInfo {OS.getHostByName 'localhost'}.name}
[edit] Pascal
For Windows systems see the Delphi example. On Unix systems, FreePascal has the function GetHostName:
Program HostName;
uses
unix;
begin
writeln('The name of this computer is: ', GetHostName);
end.
Output example on Mac OS X:
The name of this computer is: MyComputer.local
[edit] Perl
use Sys::Hostname;
$name = hostname;
[edit] Perl 6
my $host = qx[hostname];
[edit] PHP
echo $_SERVER['HTTP_HOST'];
echo php_uname('n');
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
InitNetwork()
answer$=Hostname()
[edit] Python
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] Racket
#lang racket/base
(require mzlib/os)
(gethostname)
[edit] REBOL
print system/network/host
[edit] REXX
[edit] REGINA and PC/REXX under most MS NT Windows
This REXX solution is for REGINA and PC/REXX under the Microsoft NT family of Windows (XP, Vista, 7, etc).
Other names could be used for the 3rd argument.
say value('COMPUTERNAME',,"ENVIRONMENT")
say value('OS',,"ENVIRONMENT")
output (using Windows/XP)
GERARD46 Windows_NT
[edit] R4 and ROO under most MS NT Windows
This REXX solution is for R4 and ROO under the Microsoft NT family of Windows (XP, Vista, 7, etc).
Other names could be used for the 3rd argument.
say value('COMPUTERNAME',,"SYSTEM")</lang>
say value('OS',,"SYSTEM")
[edit] MS DOS (without Windows), userid
Under Microsoft DOS (with no Windows), the closest thing to a name of a host would be the userid.
say userid()
[edit] MS DOS (without Windows), version of DOS
But perhaps the name or version of the MS DOS system would be more appropriate than the userid.
'VER' /*this passes the VER command to the MS DOS system. */
Each REXX interpreter has their own name (some have multiple names) for the environmental variables.
Different operating systems may call their hostnames by different identifiers.
IBM mainframes (at one time) called the name of the host as a nodename and it needn't be
specified, in which case an asterisk (*) is returned.
I recall (perhaps wrongly) that Windows/95 and Windows/98 had a different environmental name for the name of the host.
[edit] UNIX Solution
This solution is platform specific and uses features that are available to the Regina implementation of Rexx.
- Tested with Regina on Mac OS X. Should work on other UNIX/Linux distros.
/* Rexx */
address command "hostname -f" with output stem hn.
do q_ = 1 to hn.0
say hn.q_
end q_
exit
[edit] Ruby
require 'socket'
host = Socket.gethostname
[edit] Run BASIC
print Platform$ ' OS where Run BASIC is being hosted
print UserInfo$ ' Information about the user's web browser
print UserAddress$ ' IP address of the user
[edit] Scala
println(java.net.InetAddress.getLocalHost.getHostName)
[edit] Scheme
(use posix)
(get-host-name)
(gethostname)
[edit] Seed7
The library socket.s7i defines the function getHostname, which returns the hostname.
$ include "seed7_05.s7i";
include "socket.s7i";
const proc: main is func
begin
writeln(getHostname);
end func;
[edit] Slate
Platform current nodeName
[edit] SNOBOL4
output = host(4,"HOSTNAME")
end
[edit] Standard ML
NetHostDB.getHostName ()
[edit] Smalltalk
OperatingSystem 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] TUSCRIPT
$$ MODE TUSCRIPT
host=HOST ()
[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)
- Programming Tasks
- Programming environment operations
- Networking and Web Interaction
- Ada
- ALGOL 68
- Aikido
- AutoHotkey
- AWK
- BBC BASIC
- C
- C++
- C sharp
- Caché ObjectScript
- Clojure
- CoffeeScript
- Common Lisp
- CFFI
- D
- Delphi
- E
- E examples needing attention
- F Sharp
- Factor
- Forth
- Erlang
- Friendly interactive shell
- Fortran
- Go
- Groovy
- Haskell
- Network
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Lua
- Liberty BASIC
- Maple
- Mathematica
- MATLAB
- MIRC Scripting Language
- Modula-3
- MUMPS
- NetRexx
- NewLISP
- Objective-C
- Objeck
- OCaml
- Octave
- OoRexx
- Oz
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/SQL
- Pop11
- PowerBASIC
- PowerShell
- PureBasic
- Python
- R
- Racket
- REBOL
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Seed7
- Slate
- SNOBOL4
- Standard ML
- Smalltalk
- Tcl
- Toka
- TUSCRIPT
- UNIX Shell
- Ursala
- ACL2/Omit
- Locomotive Basic/Omit
- ML/I/Omit
- PARI/GP/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- Unlambda/Omit
- ZX Spectrum Basic/Omit