Hostname: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added COBOL)
(Add BaCon)
Line 49: Line 49:
<lang awk>$ awk 'BEGIN{print ENVIRON["HOST"]}'
<lang awk>$ awk 'BEGIN{print ENVIRON["HOST"]}'
E51A08ZD</lang>
E51A08ZD</lang>

=={{header|BaCon}}==
<lang freebasic>PRINT "Hostname: ", HOSTNAME$</lang>


=={{header|Batch File}}==
=={{header|Batch File}}==

Revision as of 08:24, 18 February 2017

Task
Hostname
You are encouraged to solve this task according to the task description, using any language you may know.
Task

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

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: POSIX version .1

<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>

AppleScript

<lang applescript> host name of (system info) </lang>

AutoHotkey

<lang AutoHotkey>MsgBox % A_ComputerName</lang>

via Windows Management Instrumentation (WMI) <lang AutoHotkey>for objItem in ComObjGet("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_ComputerSystem")

   MsgBox, % "Hostname:`t" objItem.Name</lang>

Arc

<lang Arc>(system "hostname -f")</lang>

AWK

<lang awk>$ awk 'BEGIN{print ENVIRON["HOST"]}' E51A08ZD</lang>

BaCon

<lang freebasic>PRINT "Hostname: ", HOSTNAME$</lang>

Batch File

Since Windows 2000 : <lang dos>Hostname</lang>

BBC BASIC

<lang bbcbasic> INSTALL @lib$+"SOCKLIB"

     PROC_initsockets
     PRINT "hostname: " FN_gethostname
     PROC_exitsockets</lang>

C/C++

Works with: gcc version 4.0.1
Works with: POSIX version .1

<lang c>#include <stdlib.h>

  1. include <stdio.h>
  2. include <limits.h>
  3. 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;

}</lang>

C#

<lang csharp>System.Net.Dns.GetHostName();</lang>

Caché ObjectScript

Write ##class(%SYS.System).GetNodeName()

Clojure

<lang clojure> (.. java.net.InetAddress getLocalHost getHostName) </lang>

<lang shell> java -cp clojure.jar clojure.main -e "(.. java.net.InetAddress getLocalHost getHostName)" </lang>

COBOL

<lang cobol> identification division.

      program-id. hostname.
      data division.
      working-storage section.
      01 hostname pic x(256).
      01 nullpos  pic 999 value 1.
      procedure division.
      call "gethostname" using hostname by value length of hostname
      string hostname delimited by low-value into hostname
          with pointer nullpos
      display "Host: " hostname(1 : nullpos - 1)
      goback.
      end program hostname.

</lang>

CoffeeScript

<lang coffeescript> os = require 'os' console.log os.hostname() </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 ()

   #+(or sbcl ccl) (machine-instance)
   #+clisp (let ((s (machine-instance))) (subseq s 0 (position #\Space s)))
   #-(or sbcl ccl clisp) (error "get-host-name not implemented"))</lang>
Library: CFFI

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, std.socket;

void main() {

   writeln(Socket.hostName());

}</lang>

Delphi

<lang 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.</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.

Emacs Lisp

<lang Lisp>(system-name)</lang>

F#

<lang fsharp>printfn "%s" (System.Net.Dns.GetHostName())</lang>

Factor

<lang factor>USE: io.sockets host-name</lang>

Forth

Works with: GNU Forth version 0.7.0

<lang forth>include unix/socket.fs

hostname type</lang>

Erlang

<lang Erlang>Host = net_adm:localhost().</lang>

friendly interactive shell

Translation of: UNIX Shell

<lang fishshell>hostname</lang> or <lang fishshell>uname -n</lang>

Fortran

Works with: gfortran

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>

Using fortran 2003 C-interoperability we can call posix C function gethostname (unix system call) directly

<lang fortran> program test_hostname

  use, intrinsic  :: iso_c_binding
  implicit none
  interface !to function: int gethostname(char *name, size_t namelen);
     integer(c_int) function gethostname(name, namelen) bind(c)
        use, intrinsic  :: iso_c_binding, only: c_char, c_int, c_size_t
        integer(c_size_t), value, intent(in) :: namelen
        character(len=1,kind=c_char), dimension(namelen),  intent(inout) ::  name
     end function gethostname
  end interface
  integer(c_int) :: status
  integer,parameter :: HOST_NAME_MAX=255
  character(kind=c_char,len=1),dimension(HOST_NAME_MAX) :: cstr_hostname
  integer(c_size_t) :: lenstr
  character(len=:),allocatable :: hostname
  lenstr = HOST_NAME_MAX
  status = gethostname(cstr_hostname, lenstr)
  hostname = c_to_f_string(cstr_hostname)
  write(*,*) hostname, len(hostname)
contains
  ! convert c_string to f_string
  pure function c_to_f_string(c_string) result(f_string)
     use, intrinsic :: iso_c_binding, only: c_char, c_null_char
     character(kind=c_char,len=1), intent(in) :: c_string(:)
     character(len=:), allocatable :: f_string
     integer i, n
     i = 1
     do
        if (c_string(i) == c_null_char) exit
        i = i + 1
     end do
     n = i - 1  ! exclude c_null_char
     allocate(character(len=n) :: f_string)
     f_string = transfer(c_string(1:n), f_string)
  end function c_to_f_string

end program test_hostname </lang>

FreeBASIC

<lang freebasic>' FB 1.05.0 Win64

' On Windows 10, the command line utility HOSTNAME.EXE prints the 'hostname' to the console. ' We can execute this remotely and read from its 'stdin' stream as follows:

Dim As String hostname Open Pipe "hostname" For Input As #1 Input #1, hostname Close #1 Print hostname Print Print "Press any key to quit" Sleep</lang>

Go

Use os.Hostname. <lang go>package main

import ( "fmt" "os" )

func main() { fmt.Println(os.Hostname()) }</lang>

Groovy

<lang groovy>println InetAddress.localHost.hostName</lang>

Harbour

<lang visualfoxpro>? NetName()</lang>

Haskell

Library: network

<lang haskell>import Network.BSD main = do hostName <- getHostName

         putStrLn hostName</lang>

Or if you don't want to depend on the network package being installed, you can implement it on your own (this implementation is based on the implementation in the network package).


<lang haskell>module GetHostName where

import Foreign.Marshal.Array ( allocaArray0, peekArray0 ) import Foreign.C.Types ( CInt(..), CSize(..) ) import Foreign.C.String ( CString, peekCString ) import Foreign.C.Error ( throwErrnoIfMinus1_ )

getHostName :: IO String getHostName = do

 let size = 256
 allocaArray0 size $ \ cstr -> do
   throwErrnoIfMinus1_ "getHostName" $ c_gethostname cstr (fromIntegral size)
   peekCString cstr

foreign import ccall "gethostname"

  c_gethostname :: CString -> CSize -> IO CInt

main = do hostName <- getHostName

         putStrLn hostName</lang>

Icon and Unicon

<lang icon>procedure main()

 write(&host)

end</lang>

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(final String[] args) {
 try {
  System.out.println(InetAddress.getLocalHost().getHostName());
 } catch (UnknownHostException e) { // Doesn't actually happen, but Java requires it be handled.
 }
}

}</lang>

JavaScript

Works with: JScript

<lang javascript>var network = new ActiveXObject('WScript.Network'); var hostname = network.computerName; WScript.echo(hostname);</lang>

Julia

<lang Julia> println(gethostname()) </lang>

Output:
harlan

Kotlin

<lang scala>// version 1.0.6

import java.net.InetAddress

fun main(args: Array<String>) {

   println(InetAddress.getLocalHost().hostName)

}</lang>

Lasso

This will ge the hostname as reported by the web server <lang Lasso>[web_request->httpHost]</lang> -> www.myserver.com

This will ge the hostname as reported by the system OS <lang Lasso>define host_name => thread {

data public initiated::date, // when the thread was initiated. Most likely at Lasso server startup private hostname::string // as reported by the servers hostname

public onCreate() => { .reset }

public reset() => { if(lasso_version(-lassoplatform) >> 'Win') => { protect => { local(process = sys_process('cmd',(:'hostname.exe'))) #process -> wait .hostname = string(#process -> readstring) -> trim& #process -> close } else protect => { local(process = sys_process('/bin/hostname')) #process -> wait .hostname = string(#process -> readstring) -> trim& #process -> close } } .initiated = date(date -> format(`yyyyMMddHHmmss`)) // need to set format to get rid of nasty hidden fractions of seconds .hostname -> size == 0 ? .hostname = 'undefined' }

public asString() => .hostname

}

host_name</lang> -> mymachine.local

LFE

<lang lisp> (net_adm:localhost) </lang>

Liberty BASIC

<lang lb>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$</lang>

Limbo

As with nearly anything in Inferno, it boils down to reading a file:

<lang Limbo>implement Hostname;

include "sys.m"; sys: Sys; include "draw.m";

Hostname: module { init: fn(nil: ref Draw->Context, nil: list of string); };

init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; buf := array[Sys->ATOMICIO] of byte;

fd := sys->open("/dev/sysname", Sys->OREAD); if(fd == nil) die("Couldn't open /dev/sysname");

n := sys->read(fd, buf, len buf - 1); if(n < 1) die("Couldn't read /dev/sysname");

buf[n++] = byte '\n'; sys->write(sys->fildes(1), buf, n); }

die(s: string) { sys->fprint(sys->fildes(2), "hostname: %s: %r", s); raise "fail:errors"; } </lang>

Sys->ATOMICIO is usually 8 kilobytes; this version truncates if you have a ridiculously long hostname.

Lingo

Library: Shell Xtra

<lang lingo> sx = xtra("Shell").new() if the platform contains "win" then

 hostname = sx.shell_cmd("hostname", ["eol":RETURN]).line[1] -- win 7 or later

else

 hostname = sx.shell_cmd("hostname", RETURN).line[1]

end if</lang>

LiveCode

<lang LiveCode>answer the hostName</lang>

Lua

Requires: LuaSocket <lang lua>socket = require "socket" print( socket.dns.gethostname() )</lang>

Maple

<lang Maple>Sockets:-GetHostName()</lang>

Mathematica / Wolfram Language

<lang Mathematica>$MachineName</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>

mIRC Scripting Language

<lang mirc>echo -ag $host</lang>

Modula-3

<lang modula3>MODULE Hostname EXPORTS Main;

IMPORT IO, OSConfig;

BEGIN

 IO.Put(OSConfig.HostName() & "\n");

END Hostname.</lang>

MUMPS

<lang MUMPS>Write $Piece($System,":")</lang>

NetRexx

<lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols binary

say InetAddress.getLocalHost.getHostName </lang>

NewLISP

<lang NewLISP>(! "hostname")</lang>

Nim

<lang Nim>import posix const size = 64 var s = cstring(newString(size)) discard s.getHostname(size) echo s</lang>

Oberon-2

Works with oo2c version 2 <lang oberon2> MODULE HostName; IMPORT

 OS:ProcessParameters,
 Out;

BEGIN

 Out.Object("Host: " + ProcessParameters.GetEnv("HOSTNAME"));Out.Ln

END HostName. </lang> Output:

Host: localhost.localdomain

Objective-C

Cocoa / Cocoa Touch / GNUstep:

<lang objc> NSLog(@"%@", [[NSProcessInfo processInfo] hostName]); </lang>

Example Output:

<lang objc> 2010-09-16 16:20:00.000 Playground[1319:a0f] sierra117.local // Hostname is sierra117.local. </lang>

Objeck

<lang objeck> use Net;

bundle Default {

 class Hello {
   function : Main(args : String[]) ~ Nil {
     TCPSocket->HostName()->PrintLine();
   }
 }

} </lang>

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>

ooRexx

These solutions are platform specific.

Windows Platform

A solution using ActiveX/OLE on Windows

<lang ooRexx>say .oleObject~new('WScript.Network')~computerName</lang>

and one using the Windows environment variables

<lang ooRexx>say value('COMPUTERNAME',,'environment')</lang>

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.

<lang ooRexx>address command 'hostname -f'</lang>

<lang ooRexx>address command "echo $HOSTNAME"</lang>

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:

<lang ooRexx>/* 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_

</lang>

A utility class is also provided as a wrapper around the external data queue:

<lang ooRexx>/* 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_

</lang>

Oz

<lang oz>{System.showInfo {OS.getHostByName 'localhost'}.name}</lang>

PARI/GP

Running the hostname or uname program and capturing its output (the first line of output) in a string.

<lang parigp>str = externstr("hostname")[1]; str = externstr("uname -n")[1];</lang>

Pascal

For Windows systems see the Delphi example. On Unix systems, FreePascal has the function GetHostName: <lang pascal>Program HostName;

uses

 unix;

begin

 writeln('The name of this computer is: ', GetHostName);

end.</lang> Output example on Mac OS X:

The name of this computer is: MyComputer.local

Perl

Works with: Perl version 5.8.6

<lang perl>use Sys::Hostname;

$name = hostname;</lang>

Perl 6

<lang perl6>my $host = qx[hostname];</lang>

PHP

<lang php>echo $_SERVER['HTTP_HOST'];</lang>

<lang php>echo php_uname('n');</lang>

Works with: PHP version 5.3+

<lang php>echo gethostname();</lang>

PicoLisp

This will just print the hostname: <lang PicoLisp>(call 'hostname)</lang> To use it as a string in 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

Works with: PureBasic version 4.41

<lang PureBasic>InitNetwork() answer$=Hostname()</lang>

Python

Works with: Python version 2.5

<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>

Racket

<lang Racket>

  1. lang racket/base

(require mzlib/os) (gethostname) </lang>

REBOL

<lang REBOL>print system/network/host</lang>

REXX

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.

The   computername   is the same as the output for the   hostname.exe   program. <lang REXX>say value('COMPUTERNAME',,"ENVIRONMENT") say value('OS',,"ENVIRONMENT")</lang> output (using Windows/XP)

GERARD46
Windows_NT

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. <lang REXX>say value('COMPUTERNAME',,"SYSTEM") say value('OS',,"SYSTEM")</lang>

MS DOS (without Windows), userid

Under Microsoft DOS (with no Windows), the closest thing to a name of a host would be the userid. <lang rexx>say userid()</lang>

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. <lang REXX>'VER' /*this passes the VER command to the MS DOS system. */</lang> 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.

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.

<lang REXX>/* Rexx */ address command "hostname -f" with output stem hn. do q_ = 1 to hn.0

 say hn.q_
 end q_

exit</lang>

Ruby

<lang ruby>require 'socket' host = Socket.gethostname</lang>

Run BASIC

<lang runbasic>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</lang>

Scala

<lang scala>println(java.net.InetAddress.getLocalHost.getHostName)</lang>

Scheme

Works with: Chicken Scheme

<lang scheme>(use posix) (get-host-name)</lang>

Works with: Guile

<lang scheme>(gethostname)</lang>

Seed7

The library socket.s7i defines the function getHostname, which returns the hostname.

<lang seed7>$ include "seed7_05.s7i";

 include "socket.s7i";

const proc: main is func

 begin
   writeln(getHostname);
 end func;</lang>

Sidef

<lang ruby>var sys = frequire('Sys::Hostname'); var host = sys.hostname;</lang> Or: <lang ruby>var host = `hostname`.chomp;</lang>

Slate

<lang slate>Platform current nodeName</lang>

SNOBOL4

<lang snobol4>

     output = host(4,"HOSTNAME")

end</lang>

Standard ML

<lang sml>NetHostDB.getHostName ()</lang>

Smalltalk

Works with: Smalltalk/X

<lang Smalltalk>OperatingSystem getHostName</lang>

SQL

Works with: Oracle

<lang sql> select host_name from v$instance; </lang>

Swift

Swift 3 <lang Swift>print(ProcessInfo.processInfo.hostName)</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>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT host=HOST () </lang>

UNIX Shell

<lang bash>hostname</lang> or <lang bash>uname -n</lang>

Ursa

<lang ursa>out (ursa.net.localhost.name) endl console</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>

VBScript

<lang vb> Set objNetwork = CreateObject("WScript.Network") WScript.Echo objNetwork.ComputerName </lang>

Vim Script

<lang vim>echo hostname()</lang>

zkl

<lang zkl>System.hostname</lang> Or open a server socket, which contains the hostname. <lang zkl>Network.TCPServerSocket.open(8080).hostname</lang>