
Find the name of the host on which the routine is running.
Works with GCC/GNAT
withAda.Text_IO;useAda.Text_IO;withGNAT.Sockets;procedureDemoisbeginPut_Line(GNAT.Sockets.Host_Name);endDemo;
println (System.hostname)
STRING hostname;get(read OF execve child pipe("/bin/hostname","hostname",""), hostname);print(("hostname: ", hostname, new line))hostnameof(system info)
(system "hostname -f")
printsys\hostname
drkameleons-Mac.home
MsgBox%A_ComputerName
via Windows Management Instrumentation (WMI)
forobjIteminComObjGet("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_ComputerSystem")MsgBox,%"Hostname:`t"objItem.Name
| WARNING: the following purported solution makes an assumption about environment variables that may not be applicable in all circumstances. |
$awk'BEGIN{print ENVIRON["HOST"]}'E51A08ZD
PRINT"Hostname: ",HOSTNAME$
Since Windows 2000 :
Hostname
To assign it to a variable:
for/f"tokens=*"%%ain('hostname')doset"hostname=%%a"
Hostname.exe will not print out the correct hostname if%_CLUSTER_NETWORK_NAME_% is populated.[1]
Alternatively, use%COMPUTERNAME% (shell variable):[2]
setcomputername
echo%computername%
This variable can be changed to another value.
You can also get hostname values from the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\ComputerNameHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\ComputerNameHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\HostnameHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NVHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DomainHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NV Domain
More details here:https://groups.google.com/g/microsoft.public.win32.programmer.kernel/c/HI-c-Le7360
INSTALL@lib$+"SOCKLIB"PROC_initsocketsPRINT"hostname: "FN_gethostnamePROC_exitsockets
#include<stdlib.h>#include<stdio.h>#include<limits.h>#include<unistd.h>intmain(void){charname[_POSIX_HOST_NAME_MAX+1];returngethostname(name,sizeofname)==-1||printf("%s\n",name)<0?EXIT_FAILURE:EXIT_SUCCESS;}
System.Net.Dns.GetHostName();
Write ##class(%SYS.System).GetNodeName()
(..java.net.InetAddressgetLocalHostgetHostName)
java-cpclojure.jarclojure.main-e"(.. java.net.InetAddress getLocalHost getHostName)"identificationdivision.program-id.hostname.datadivision.working-storagesection.01hostnamepic x(256).01nullpospic 999value1.proceduredivision.call"gethostname"usinghostnamebyvaluelengthofhostnamestringhostnamedelimitedbylow-valueintohostnamewithpointernullposdisplay"Host: "hostname(1:nullpos-1)goback.endprogramhostname.
os=require'os'console.logos.hostname()
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.
(defunget-host-name()#+(orsbclccl)(machine-instance)#+clisp(let((s(machine-instance)))(subseqs0(position#\Spaces)))#-(orsbclcclclisp)(error"get-host-name not implemented"))
Another way is to use theFFI to access POSIX'gethostname(2):
(cffi:defcfun("gethostname"c-gethostname):int(buf:pointer)(len:unsigned-long))(defunget-hostname()(cffi:with-foreign-object(buf:char256)(unless(zerop(c-gethostnamebuf256))(error"Can't get hostname"))(values(cffi:foreign-string-to-lispbuf))))
BOA>(get-hostname)"aurora"
hostname=System.hostname
importstd.stdio,std.socket;voidmain(){writeln(Socket.hostName());}
programShowHostName;{$APPTYPE CONSOLE}usesWindows;varlHostName:array[0..255]ofchar;lBufferSize:DWORD;beginlBufferSize:=256;ifGetComputerName(lHostName,lBufferSize)thenWriteln(lHostName)elseWriteln('error getting host name');end.
If the environment variable HOSTNAME has been exported to the DuckDB environment,its value can be obtained using the getenv() function. For example:
$ HOSTNAME=`hostname` duckdb -c "select getenv('HOSTNAME');"┌────────────────────┐│ getenv('HOSTNAME') ││ varchar │├────────────────────┤│ Mac-mini.local │└────────────────────┘Assuming that DuckDB is executing in an environment in which there isa `hostname` command, the hostname can be viewed using one of DuckDB's"dot" commands as illustrated here:
.system hostnameMac-mini.local
The value so obtained, however, is not directly available as an SQL value.This can be overcome by using one of the following workarounds:
`shellfs` is a community extension which can also be used toimport the hostname as follows:
D INSTALL shellfs from community; -- once is enoughD LOAD shellfs;D SELECT * from read_csv('hostname|', header=false, columns={'hostname': 'VARCHAR'});┌────────────────┐│ hostname ││ varchar │├────────────────┤│ Mac-mini.local │└────────────────┘One can also use DuckDB to generate the string for creating a suitablescalar function or variable, and then using `.read` to execute thatstring.
For example, using "SET VARIABLE" (introduced in DuckDB V1.1), you could proceed as follows:
D .shell hostname | sed -e 's/^/set variable hostname=\"/; s/$/\";/' > dynamic.tmpD .read dynamic.tmpD SELECT getvariable('hostname');┌─────────────────────────┐│ getvariable('hostname') ││ varchar │├─────────────────────────┤│ Mac-mini.local │└─────────────────────────┘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.
(system-name)
Host=net_adm:localhost().
printfn"%s"(System.Net.Dns.GetHostName())
USE:io.socketshost-name
includeunix/socket.fshostnametype
The function/subroutineHOSTNM is a GNU extension.
programHostTestcharacter(len=128)::namecallhostnm(name)print*,nameend programHostTest
Using fortran 2003 C-interoperability we can call posix C function gethostname (unix system call) directly
programtest_hostnameuse,intrinsic::iso_c_bindingimplicit none interface!to function: int gethostname(char *name, size_t namelen);integer(c_int)functiongethostname(name,namelen)bind(c)use,intrinsic::iso_c_binding,only:c_char,c_int,c_size_t integer(c_size_t),value,intent(in)::namelencharacter(len=1,kind=c_char),dimension(namelen),intent(inout)::nameend functiongethostnameend interfaceinteger(c_int)::statusinteger,parameter::HOST_NAME_MAX=255character(kind=c_char,len=1),dimension(HOST_NAME_MAX)::cstr_hostnameinteger(c_size_t)::lenstrcharacter(len=:),allocatable::hostnamelenstr=HOST_NAME_MAXstatus=gethostname(cstr_hostname,lenstr)hostname=c_to_f_string(cstr_hostname)write(*,*)hostname,len(hostname)contains! convert c_string to f_stringpure functionc_to_f_string(c_string)result(f_string)use,intrinsic::iso_c_binding,only:c_char,c_null_charcharacter(kind=c_char,len=1),intent(in)::c_string(:)character(len=:),allocatable::f_stringintegeri,ni=1do if(c_string(i)==c_null_char)exiti=i+1end don=i-1! exclude c_null_charallocate(character(len=n)::f_string)f_string=transfer(c_string(1:n),f_string)end functionc_to_f_stringend programtest_hostname
' 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:DimAsStringhostnameOpenPipe"hostname"ForInputAs#1Input#1,hostnameClose#1PrinthostnamePrintPrint"Press any key to quit"Sleep
hostname
or
uname -n
callJava["java.net.InetAddress", "getLocalHost"].getHostName[]
include "NSLog.incl"NSLog( @"%@", fn ProcessInfoHostName )HandleEvents
Click this link to run this code
PublicSubMain()PrintSystem.HostEnd
Output:
charlie
Useos.Hostname.
packagemainimport("fmt""os")funcmain(){fmt.Println(os.Hostname())}
printlnInetAddress.localHost.hostName
? NetName()
importNetwork.BSDmain=dohostName<-getHostNameputStrLnhostName
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).
moduleGetHostNamewhereimportForeign.Marshal.Array(allocaArray0,peekArray0)importForeign.C.Types(CInt(..),CSize(..))importForeign.C.String(CString,peekCString)importForeign.C.Error(throwErrnoIfMinus1_)getHostName::IOStringgetHostName=doletsize=256allocaArray0size$\cstr->dothrowErrnoIfMinus1_"getHostName"$c_gethostnamecstr(fromIntegralsize)peekCStringcstrforeignimportccall"gethostname"c_gethostname::CString->CSize->IOCIntmain=dohostName<-getHostNameputStrLnhostName
proceduremain()write(&host)end
hostname=GETENV('computername')
NB. Load the socket librariesload'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:>{:sdgethostnamecoinsert'jsocket'[load'socket'
importjava.net.InetAddress;importjava.net.UnknownHostException;
voidprintHostname()throwsUnknownHostException{InetAddresslocalhost=InetAddress.getLocalHost();System.out.println(localhost.getHostName());}
penguin
varnetwork=newActiveXObject('WScript.Network');varhostname=network.computerName;WScript.echo(hostname);
Currently jq does not have a "gethostname" or a "system" command, so the best ways for a jq program to have access to the hostname are via an environment variable, or via a command line argument, as illustrated here:
HOST=$(hostname) jq -n --arg hostname $(hostname) '[env.HOST, $hostname]'
[ "mini.local", "mini.local"]
varhn=exec("hostname",{retAll:true}).data.trim();
println(gethostname())
harlan
_h
`"narasimman-pc"
// version 1.1.4importjava.net.InetAddressfunmain(args:Array<String>){println(InetAddress.getLocalHost().hostName)}
This will ge the hostname as reported by the web server
[web_request->httpHost]
-> www.myserver.com
This will ge the hostname as reported by the system OS
definehost_name=>thread{datapublicinitiated::date,// when the thread was initiated. Most likely at Lasso server startupprivatehostname::string// as reported by the servers hostnamepubliconCreate()=>{.reset}publicreset()=>{if(lasso_version(-lassoplatform)>>'Win')=>{protect=>{local(process=sys_process('cmd',(:'hostname.exe')))#process->wait.hostname=string(#process->readstring)->trim&#process->close}elseprotect=>{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'}publicasString()=>.hostname}host_name
-> mymachine.local
(net_adm:localhost)
lpBuffer$=Space$(128) + Chr$(0)struct SIZE,sz As LongSIZE.sz.struct=Len(lpBuffer$)calldll #kernel32, "GetComputerNameA",lpBuffer$ as ptr, SIZE as struct, result as LongCurrentComputerName$=Trim$(Left$(lpBuffer$, SIZE.sz.struct))print CurrentComputerName$
As with nearly anything in Inferno, it boils down to reading a file:
implementHostname;include"sys.m";sys:Sys;include"draw.m";Hostname:module{init:fn(nil:refDraw->Context,nil:listofstring);};init(nil:refDraw->Context,nil:listofstring){sys=loadSysSys->PATH;buf:=array[Sys->ATOMICIO]ofbyte;fd:=sys->open("/dev/sysname",Sys->OREAD);if(fd==nil)die("Couldn't open /dev/sysname");n:=sys->read(fd,buf,lenbuf-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";}
Sys->ATOMICIO is usually 8 kilobytes; this version truncates if you have a ridiculously long hostname.
sx = xtra("Shell").new()if the platform contains "win" then hostname = sx.shell_cmd("hostname", ["eol":RETURN]).line[1] -- win 7 or laterelse hostname = sx.shell_cmd("hostname", RETURN).line[1]end ifanswer the hostName
Requires: LuaSocket
socket=require"socket"print(socket.dns.gethostname())
Module Host { \\ one way Print computer$ \\ second way Declare objNetwork "WScript.Network" With objNetwork, "ComputerName" as cName$ Print cName$, cName$=Computer$ Declare objNetwork Nothing}HostSockets:-GetHostName()
$MachineName
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 commandhostname exists.
[failed,hostname]=system('hostname')
echo -ag $host
MODULEHostnameEXPORTSMain;IMPORTIO,OSConfig;BEGINIO.Put(OSConfig.HostName()&"\n");ENDHostname.
Write $Piece($System,":")
/* NetRexx */optionsreplaceformatcommentsjavacrossrefsavelogsymbolsbinarysayInetAddress.getLocalHost.getHostName
(!"hostname")
There are several ways to get the host name, for instance reading the environment variable HOSTNAME or calling the low level Posix function “gethostname”. The simplest way consists to use the function “getHostName” from module “nativeSockets”:
importnativesocketsechogetHostName()
Works with oo2c version 2
MODULEHostName;IMPORTOS:ProcessParameters,Out;BEGINOut.Object("Host: "+ProcessParameters.GetEnv("HOSTNAME"));Out.LnENDHostName.
Output:
Host: localhost.localdomain
use Net;bundle Default { class Hello { function : Main(args : String[]) ~ Nil { TCPSocket->HostName()->PrintLine(); } }}Cocoa / Cocoa Touch / GNUstep:
NSLog(@"%@",[[NSProcessInfoprocessInfo]hostName]);
Example Output:
2010-09-1616:20:00.000Playground[1319:a0f]sierra117.local// Hostname is sierra117.local.
Unix.gethostname()
Similarly toMATLAB, we could call system commandhostname to know the hostname. But we can also call the internal functionuname() which returns a structure holding several informations, among these the hostname (nodename):
uname().nodename
These solutions are platform specific.
A solution using ActiveX/OLE on Windows
say.oleObject~new('WScript.Network')~computerName
and one using the Windows environment variables
sayvalue('COMPUTERNAME',,'environment')
Some UNIX solutions (tested under Mac OS X):
ooRexx (andRexx) 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.
addresscommand'hostname -f'
addresscommand"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 intorxqueue which sends it in turn to a Rexx queue for further processing by the program:
/* Rexx */addresscommand"echo $HOSTNAME | rxqueue"addresscommand"hostname -f | rxqueue"loopq_=1whilequeued()>0parsepullhnsayq_~right(2)':'hnendq_
A utility class is also provided as a wrapper around the external data queue:
/* Rexx */qq=.rexxqueue~new()addresscommand"echo $HOSTNAME | rxqueue"addresscommand"hostname -f | rxqueue"loopq_=1whileqq~queued()>0hn=qq~pull()sayq_~right(2)':'hnendq_
{System.showInfo {OS.getHostByName 'localhost'}.name}Running thehostname oruname program and capturing its output (the first line of output) in a string.
str = externstr("hostname")[1];str = externstr("uname -n")[1];For Windows systems see the Delphi example.On Unix systems, FreePascal has the function GetHostName:
ProgramHostName;usesunix;beginwriteln('The name of this computer is: ',GetHostName);end.
Output example on Mac OS X:
The name of this computer is: MyComputer.local
##System.Net.Dns.GetHostName.Print
useSys::Hostname;$name=hostname;
withoutjs-- (system_exec, file i/o)constanttmp="hostname.txt",cmd=iff(platform()=WINDOWS?"hostname":"uname -n"){}=system_exec(sprintf("%s > %s",{cmd,tmp}),4)stringhost=trim(get_text(tmp)){}=delete_file(tmp)?host
"Pete-PC"
echo$_SERVER['HTTP_HOST'];
echophp_uname('n');
echogethostname();
This will just print the hostname:
(call 'hostname)
To use it as a string in a program:
(in '(hostname) (line T))
importSystem;intmain(){write(gethostname()+"\n");}
os.execute("hostname > tmp")localhostname=io.contents("tmp"):rstrip()print($"Hostname is {hostname}")os.remove("tmp")
SETserveroutputonBEGINDBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);END;
lvars host = sys_host_name();
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$
Windows systems have theComputerName environment variable which can be used:
$Env:COMPUTERNAMEAlso PowerShell can use .NET classes and methods:
[Net.Dns]::GetHostName()
InitNetwork()answer$=Hostname()
importsockethost=socket.gethostname()
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)
#langracket/base(requireracket/os)(gethostname)
(formerly Perl 6)
my$host =qx[hostname];
printreaddns://
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.
sayvalue('COMPUTERNAME',,"ENVIRONMENT")sayvalue('OS',,"ENVIRONMENT")
output (using Windows/XP)
GERARD46Windows_NT
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.
sayvalue('COMPUTERNAME',,"SYSTEM")sayvalue('OS',,"SYSTEM")
Under Microsoft DOS (with no Windows), the closest thing to a name of a host would be the userid.
sayuserid()
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 anodename 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.
This solution is platform specific and uses features that are available to the Regina implementation of Rexx.
/* Rexx */addresscommand"hostname -f"withoutputstemhn.doq_=1tohn.0sayhn.q_endq_exit
require'socket'host=Socket.gethostname
print Platform$ ' OS where Run BASIC is being hostedprint UserInfo$ ' Information about the user's web browserprint UserAddress$ ' IP address of the user
Works on windows and linux with cratehostname version 0.1.5
fn main() { match hostname::get_hostname() { Some(host) => println!("hostname: {}", host), None => eprintln!("Could not get hostname!"), }}println(java.net.InetAddress.getLocalHost.getHostName)
(use posix)(get-host-name)
(gethostname)
The librarysocket.s7idefines the functiongetHostname,which returns the hostname.
$ include "seed7_05.s7i"; include "socket.s7i";const proc: main is func begin writeln(getHostname); end func;
var sys = frequire('Sys::Hostname');var host = sys.hostname;Or:
var host = `hostname`.chomp;
Platform current nodeName
(hostname)
OperatingSystem getHostName
output = host(4,"HOSTNAME")end
select host_name from v$instance;
SELECT HOST_NAME FROM SYSIBMADM.ENV_SYS_INFO
Output:
HOST_NAME ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------hostname 1 record(s) selected.
NetHostDB.getHostName ()
Swift 3
print(ProcessInfo.processInfo.hostName)
The basic introspection tool in TCL is theinfo 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]
2 import gethostname1024 chars is-array foofoo 1024 gethostnamefoo type
$$ MODE TUSCRIPThost=HOST ()
hostname
or
uname -n
out (ursa.net.localhost.name) endl console
The user-defined hostname function ignores its argument and returns a string.
#import clihostname = ~&hmh+ (ask bash)/<>+ <'hostname'>!
For example, the following function returns the square root of its argumentif it's running on host kremvax, but otherwise returns the square.
#import flocreative_accounting = (hostname== 'kremvax')?(sqrt,sqr)
Set objNetwork = CreateObject("WScript.Network")WScript.Echo objNetwork.ComputerNameecho hostname()
Option ExplicitPrivate Declare Function GetComputerName Lib "kernel32.dll" Alias "GetComputerNameW" _ (ByVal lpBuffer As Long, ByRef nSize As Long) As Long Private Const MAX_COMPUTERNAME_LENGTH As Long = 31Private Const NO_ERR As Long = 0Private Function Hostname() As StringDim i As Long, l As Long, s As String s = Space$(MAX_COMPUTERNAME_LENGTH) l = Len(s) + 1 i = GetComputerName(StrPtr(s), l) Debug.Assert i <> 0 Debug.Assert l <> 0 Hostname = Left$(s, l)End FunctionSub Main() Debug.Assert Hostname() = Environ$("COMPUTERNAME")End SubIn Vlang, the "main()" entry point and declaration can be skipped in one file programs and when used like a script.
import osprintln(os.hostname())
Uses the 'os' sub-module.
import "os" for PlatformSystem.print(Platform.hostName)
System.hostname
Or open a server socket, which contains the hostname.
Network.TCPServerSocket.open(8080).hostname