Hostname: Difference between revisions

From Rosetta Code
Content added Content deleted
(added Crystal implementation)
m (→‎{{header|Wren}}: Minor tidy)
 
(13 intermediate revisions by 12 users not shown)
Line 8: Line 8:
=={{header|Ada}}==
=={{header|Ada}}==
Works with GCC/GNAT
Works with GCC/GNAT
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Sockets;
with GNAT.Sockets;


Line 14: Line 14:
begin
begin
Put_Line (GNAT.Sockets.Host_Name);
Put_Line (GNAT.Sockets.Host_Name);
end Demo;</lang>
end Demo;</syntaxhighlight>

=={{header|Aikido}}==
<syntaxhighlight lang="aikido">
println (System.hostname)
</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 22: Line 27:
<!-- {{does not works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - No such library function.}} -->
<!-- {{does not works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - No such library function.}} -->
{{works with|POSIX|.1}}
{{works with|POSIX|.1}}
<lang algol68>STRING hostname;
<syntaxhighlight lang="algol68">STRING hostname;
get(read OF execve child pipe("/bin/hostname","hostname",""), hostname);
get(read OF execve child pipe("/bin/hostname","hostname",""), hostname);
print(("hostname: ", hostname, new line))</lang>
print(("hostname: ", hostname, new line))</syntaxhighlight>

=={{header|Aikido}}==
<lang aikido>
println (System.hostname)
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang applescript>
<syntaxhighlight lang="applescript">
host name of (system info)
host name of (system info)
</syntaxhighlight>
</lang>

=={{header|Arc}}==
<syntaxhighlight lang="arc">(system "hostname -f")</syntaxhighlight>

=={{header|Arturo}}==

<syntaxhighlight lang="arturo">print sys\hostname</syntaxhighlight>

{{out}}

<pre>drkameleons-Mac.home</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox % A_ComputerName</lang>
<syntaxhighlight lang="autohotkey">MsgBox % A_ComputerName</syntaxhighlight>


via Windows Management Instrumentation (WMI)
via Windows Management Instrumentation (WMI)
<lang AutoHotkey>for objItem in ComObjGet("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_ComputerSystem")
<syntaxhighlight lang="autohotkey">for objItem in ComObjGet("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_ComputerSystem")
MsgBox, % "Hostname:`t" objItem.Name</lang>
MsgBox, % "Hostname:`t" objItem.Name</syntaxhighlight>

=={{header|Arc}}==
<lang Arc>(system "hostname -f")</lang>


=={{header|AWK}}==
=={{header|AWK}}==


{{noticebox||WARNING: the following purported solution makes an assumption about environment variables that may not be applicable in all circumstances.}}
{{noticebox||WARNING: the following purported solution makes an assumption about environment variables that may not be applicable in all circumstances.}}
<lang awk>$ awk 'BEGIN{print ENVIRON["HOST"]}'
<syntaxhighlight lang="awk">$ awk 'BEGIN{print ENVIRON["HOST"]}'
E51A08ZD</lang>
E51A08ZD</syntaxhighlight>


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


=={{header|Batch File}}==
=={{header|Batch File}}==
Since Windows 2000 :
Since Windows 2000 :
<lang dos>Hostname</lang>
<syntaxhighlight lang="dos">Hostname</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INSTALL @lib$+"SOCKLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SOCKLIB"
PROC_initsockets
PROC_initsockets
PRINT "hostname: " FN_gethostname
PRINT "hostname: " FN_gethostname
PROC_exitsockets</lang>
PROC_exitsockets</syntaxhighlight>


=={{header|C}}/{{header|C++}}==
=={{header|C}}/{{header|C++}}==
Line 70: Line 78:


{{works with|POSIX|.1}}
{{works with|POSIX|.1}}
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <limits.h>
#include <limits.h>
Line 79: Line 87:
char name[_POSIX_HOST_NAME_MAX + 1];
char name[_POSIX_HOST_NAME_MAX + 1];
return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>System.Net.Dns.GetHostName();</lang>
<syntaxhighlight lang="csharp">System.Net.Dns.GetHostName();</syntaxhighlight>


=={{header|Caché ObjectScript}}==
=={{header|Caché ObjectScript}}==
Line 89: Line 97:
=={{header|Clojure}}==
=={{header|Clojure}}==


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


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


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. hostname.
program-id. hostname.


Line 113: Line 121:
goback.
goback.
end program hostname.
end program hostname.
</syntaxhighlight>
</lang>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
os = require 'os'
os = require 'os'
console.log os.hostname()
console.log os.hostname()
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|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.
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 ()
<syntaxhighlight lang="lisp">(defun get-host-name ()
#+(or sbcl ccl) (machine-instance)
#+(or sbcl ccl) (machine-instance)
#+clisp (let ((s (machine-instance))) (subseq s 0 (position #\Space s)))
#+clisp (let ((s (machine-instance))) (subseq s 0 (position #\Space s)))
#-(or sbcl ccl clisp) (error "get-host-name not implemented"))</lang>
#-(or sbcl ccl clisp) (error "get-host-name not implemented"))</syntaxhighlight>


{{libheader|CFFI}}
{{libheader|CFFI}}
Line 132: Line 140:
Another way is to use the [[FFI]] to access POSIX' <code>gethostname(2)</code>:
Another way is to use the [[FFI]] to access POSIX' <code>gethostname(2)</code>:


<lang lisp>(cffi:defcfun ("gethostname" c-gethostname) :int
<syntaxhighlight lang="lisp">(cffi:defcfun ("gethostname" c-gethostname) :int
(buf :pointer) (len :unsigned-long))
(buf :pointer) (len :unsigned-long))


Line 139: Line 147:
(unless (zerop (c-gethostname buf 256))
(unless (zerop (c-gethostname buf 256))
(error "Can't get hostname"))
(error "Can't get hostname"))
(values (cffi:foreign-string-to-lisp buf))))</lang>
(values (cffi:foreign-string-to-lisp buf))))</syntaxhighlight>


<lang lisp>BOA> (get-hostname)
<syntaxhighlight lang="lisp">BOA> (get-hostname)
"aurora"</lang>
"aurora"</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang crystal>hostname = System.hostname</lang>
<syntaxhighlight lang="crystal">hostname = System.hostname</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.socket;
<syntaxhighlight lang="d">import std.stdio, std.socket;


void main() {
void main() {
writeln(Socket.hostName());
writeln(Socket.hostName());
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program ShowHostName;
<syntaxhighlight lang="delphi">program ShowHostName;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 170: Line 178:
else
else
Writeln('error getting host name');
Writeln('error getting host name');
end.</lang>
end.</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==


<lang e>makeCommand("hostname")()[0].trim()</lang>
<syntaxhighlight lang="e">makeCommand("hostname")()[0].trim()</syntaxhighlight>


Not exactly a good way to do it. A better way ought to be introduced along with a proper socket interface. [[Category:E examples needing attention]]
Not exactly a good way to do it. A better way ought to be introduced along with a proper socket interface. [[Category:E examples needing attention]]


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(system-name)</lang>
<syntaxhighlight lang="lisp">(system-name)</syntaxhighlight>

=={{header|Erlang}}==
<syntaxhighlight lang="erlang">Host = net_adm:localhost().</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>printfn "%s" (System.Net.Dns.GetHostName())</lang>
<syntaxhighlight lang="fsharp">printfn "%s" (System.Net.Dns.GetHostName())</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USE: io.sockets
<syntaxhighlight lang="factor">USE: io.sockets
host-name</lang>
host-name</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth|0.7.0}}
{{works with|GNU Forth|0.7.0}}
<lang forth>include unix/socket.fs
<syntaxhighlight lang="forth">include unix/socket.fs


hostname type</lang>
hostname type</syntaxhighlight>

=={{header|Erlang}}==
<lang Erlang>Host = net_adm:localhost().</lang>

=={{header|friendly interactive shell}}==
{{trans|UNIX Shell}}

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


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 208: Line 209:


The function/subroutine <tt>HOSTNM</tt> is a GNU extension.
The function/subroutine <tt>HOSTNM</tt> is a GNU extension.
<lang fortran>program HostTest
<syntaxhighlight lang="fortran">program HostTest
character(len=128) :: name
character(len=128) :: name
call hostnm(name)
call hostnm(name)
print *, name
print *, name
end program HostTest</lang>
end program HostTest</syntaxhighlight>


Using fortran 2003 C-interoperability we can call posix C function gethostname (unix system call) directly
Using fortran 2003 C-interoperability we can call posix C function gethostname (unix system call) directly
<lang fortran>
<syntaxhighlight lang="fortran">
program test_hostname
program test_hostname
use, intrinsic :: iso_c_binding
use, intrinsic :: iso_c_binding
Line 255: Line 256:


end program test_hostname
end program test_hostname
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


' On Windows 10, the command line utility HOSTNAME.EXE prints the 'hostname' to the console.
' On Windows 10, the command line utility HOSTNAME.EXE prints the 'hostname' to the console.
Line 270: Line 271:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>

=={{header|friendly interactive shell}}==
{{trans|UNIX Shell}}

<syntaxhighlight lang="fishshell">hostname</syntaxhighlight>
or
<syntaxhighlight lang="fishshell">uname -n</syntaxhighlight>

=={{header|Frink}}==
<syntaxhighlight lang="frink">callJava["java.net.InetAddress", "getLocalHost"].getHostName[]</syntaxhighlight>


=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
NSLog( @"%@", fn ProcessInfoHostName )
HandleEvents
</syntaxhighlight>



=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=11d7f489117d7909da509050103b7891 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=11d7f489117d7909da509050103b7891 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()


Print System.Host
Print System.Host


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 286: Line 306:
=={{header|Go}}==
=={{header|Go}}==
Use [https://golang.org/pkg/os/#Hostname <code>os.Hostname</code>].
Use [https://golang.org/pkg/os/#Hostname <code>os.Hostname</code>].
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 295: Line 315:
func main() {
func main() {
fmt.Println(os.Hostname())
fmt.Println(os.Hostname())
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==


<lang groovy>println InetAddress.localHost.hostName</lang>
<syntaxhighlight lang="groovy">println InetAddress.localHost.hostName</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
<lang visualfoxpro>? NetName()</lang>
<syntaxhighlight lang="visualfoxpro">? NetName()</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
{{libheader|network}}
{{libheader|network}}
<lang haskell>import Network.BSD
<syntaxhighlight lang="haskell">import Network.BSD
main = do hostName <- getHostName
main = do hostName <- getHostName
putStrLn hostName</lang>
putStrLn hostName</syntaxhighlight>


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).
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
<syntaxhighlight lang="haskell">module GetHostName where


import Foreign.Marshal.Array ( allocaArray0, peekArray0 )
import Foreign.Marshal.Array ( allocaArray0, peekArray0 )
Line 331: Line 351:


main = do hostName <- getHostName
main = do hostName <- getHostName
putStrLn hostName</lang>
putStrLn hostName</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
write(&host)
write(&host)
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
<lang idl>hostname = GETENV('computername')</lang>
<syntaxhighlight lang="idl">hostname = GETENV('computername')</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>NB. Load the socket libraries
<syntaxhighlight lang="j">NB. Load the socket libraries


load 'socket'
load 'socket'
Line 354: Line 374:
NB. and the hostname is fetched only once, then use a 'one-liner' to accomplish it:
NB. and the hostname is fetched only once, then use a 'one-liner' to accomplish it:


> {: sdgethostname coinsert 'jsocket' [ load 'socket'</lang>
> {: sdgethostname coinsert 'jsocket' [ load 'socket'</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.net.*;
<syntaxhighlight lang="java">
import java.net.InetAddress;
class DiscoverHostName {
import java.net.UnknownHostException;
public static void main(final String[] args) {
</syntaxhighlight>
try {
<syntaxhighlight lang="java">
System.out.println(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) { // Doesn't actually happen, but Java requires it be handled.
void printHostname() throws UnknownHostException {
InetAddress localhost = InetAddress.getLocalHost();
}
System.out.println(localhost.getHostName());
}
}
}</lang>
</syntaxhighlight>
<pre>
penguin
</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|JScript}}
{{works with|JScript}}
<lang javascript>var network = new ActiveXObject('WScript.Network');
<syntaxhighlight lang="javascript">var network = new ActiveXObject('WScript.Network');
var hostname = network.computerName;
var hostname = network.computerName;
WScript.echo(hostname);</lang>
WScript.echo(hostname);</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 383: Line 407:


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>var hn = exec("hostname", {retAll:true}).data.trim();</lang>
<syntaxhighlight lang="javascript">var hn = exec("hostname", {retAll:true}).data.trim();</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
println(gethostname())
println(gethostname())
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 396: Line 420:


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
_h
_h
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 406: Line 430:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.4
<syntaxhighlight lang="scala">// version 1.1.4


import java.net.InetAddress
import java.net.InetAddress
Line 412: Line 436:
fun main(args: Array<String>) {
fun main(args: Array<String>) {
println(InetAddress.getLocalHost().hostName)
println(InetAddress.getLocalHost().hostName)
}</lang>
}</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
This will ge the hostname as reported by the web server
This will ge the hostname as reported by the web server
<lang Lasso>[web_request->httpHost]</lang>
<syntaxhighlight lang="lasso">[web_request->httpHost]</syntaxhighlight>
-> www.myserver.com
-> www.myserver.com


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


data
data
Line 454: Line 478:
}
}


host_name</lang>
host_name</syntaxhighlight>
-> mymachine.local
-> mymachine.local


=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>
<syntaxhighlight lang="lisp">
(net_adm:localhost)
(net_adm:localhost)
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>lpBuffer$=Space$(128) + Chr$(0)
<syntaxhighlight lang="lb">lpBuffer$=Space$(128) + Chr$(0)
struct SIZE,sz As Long
struct SIZE,sz As Long
SIZE.sz.struct=Len(lpBuffer$)
SIZE.sz.struct=Len(lpBuffer$)
Line 471: Line 495:
CurrentComputerName$=Trim$(Left$(lpBuffer$, SIZE.sz.struct))
CurrentComputerName$=Trim$(Left$(lpBuffer$, SIZE.sz.struct))


print CurrentComputerName$</lang>
print CurrentComputerName$</syntaxhighlight>


=={{header|Limbo}}==
=={{header|Limbo}}==
As with nearly anything in Inferno, it boils down to reading a file:
As with nearly anything in Inferno, it boils down to reading a file:


<lang Limbo>implement Hostname;
<syntaxhighlight lang="limbo">implement Hostname;


include "sys.m"; sys: Sys;
include "sys.m"; sys: Sys;
Line 507: Line 531:
raise "fail:errors";
raise "fail:errors";
}
}
</syntaxhighlight>
</lang>


Sys->ATOMICIO is usually 8 kilobytes; this version truncates if you have a ridiculously long hostname.
Sys->ATOMICIO is usually 8 kilobytes; this version truncates if you have a ridiculously long hostname.
Line 513: Line 537:
=={{header|Lingo}}==
=={{header|Lingo}}==
{{libheader|Shell Xtra}}
{{libheader|Shell Xtra}}
<lang lingo>
<syntaxhighlight lang="lingo">
sx = xtra("Shell").new()
sx = xtra("Shell").new()
if the platform contains "win" then
if the platform contains "win" then
Line 519: Line 543:
else
else
hostname = sx.shell_cmd("hostname", RETURN).line[1]
hostname = sx.shell_cmd("hostname", RETURN).line[1]
end if</lang>
end if</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>answer the hostName</lang>
<syntaxhighlight lang="livecode">answer the hostName</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Requires: LuaSocket
Requires: LuaSocket
<lang lua>socket = require "socket"
<syntaxhighlight lang="lua">socket = require "socket"
print( socket.dns.gethostname() )</lang>
print( socket.dns.gethostname() )</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Host {
Module Host {
\\ one way
\\ one way
Line 541: Line 565:
}
}
Host
Host
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>Sockets:-GetHostName()</lang>
<syntaxhighlight lang="maple">Sockets:-GetHostName()</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>$MachineName</lang>
<syntaxhighlight lang="mathematica">$MachineName</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|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 <tt>hostname</tt> exists.
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 <tt>hostname</tt> exists.


<lang Matlab>[failed,hostname] = system('hostname')</lang>
<syntaxhighlight lang="matlab">[failed,hostname] = system('hostname')</syntaxhighlight>


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==
<lang mirc>echo -ag $host</lang>
<syntaxhighlight lang="mirc">echo -ag $host</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Hostname EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Hostname EXPORTS Main;


IMPORT IO, OSConfig;
IMPORT IO, OSConfig;
Line 564: Line 588:
BEGIN
BEGIN
IO.Put(OSConfig.HostName() & "\n");
IO.Put(OSConfig.HostName() & "\n");
END Hostname.</lang>
END Hostname.</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>Write $Piece($System,":")</lang>
<syntaxhighlight lang="mumps">Write $Piece($System,":")</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
options replace format comments java crossref savelog symbols binary


say InetAddress.getLocalHost.getHostName
say InetAddress.getLocalHost.getHostName
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(! "hostname")</lang>
<syntaxhighlight lang="newlisp">(! "hostname")</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
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”:
<lang Nim>import posix
<syntaxhighlight lang="nim">import nativesockets
const size = 64
echo getHostName()</syntaxhighlight>
var s = cstring(newString(size))
discard s.getHostname(size)
echo s</lang>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c version 2
Works with oo2c version 2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE HostName;
MODULE HostName;
IMPORT
IMPORT
Line 596: Line 618:
Out.Object("Host: " + ProcessParameters.GetEnv("HOSTNAME"));Out.Ln
Out.Object("Host: " + ProcessParameters.GetEnv("HOSTNAME"));Out.Ln
END HostName.
END HostName.
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Host: localhost.localdomain
Host: localhost.localdomain
</pre>
</pre>
=={{header|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>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use Net;
use Net;


Line 626: Line 635:
}
}
}
}
</syntaxhighlight>
</lang>

=={{header|Objective-C}}==

Cocoa / Cocoa Touch / GNUstep:

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

Example Output:

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


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>Unix.gethostname()</lang>
<syntaxhighlight lang="ocaml">Unix.gethostname()</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
Similarly to [[Discover the Hostname#MATLAB|MATLAB]], we could call system command <tt>hostname</tt> to know the hostname. But we can also call the internal function <tt>uname()</tt> which returns a structure holding several informations, among these the hostname (nodename):
Similarly to [[Discover the Hostname#MATLAB|MATLAB]], we could call system command <tt>hostname</tt> to know the hostname. But we can also call the internal function <tt>uname()</tt> which returns a structure holding several informations, among these the hostname (nodename):


<lang octave>uname().nodename</lang>
<syntaxhighlight lang="octave">uname().nodename</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
Line 641: Line 664:
A solution using ActiveX/OLE on Windows
A solution using ActiveX/OLE on Windows


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


and one using the Windows environment variables
and one using the Windows environment variables


<lang ooRexx>say value('COMPUTERNAME',,'environment')</lang>
<syntaxhighlight lang="oorexx">say value('COMPUTERNAME',,'environment')</syntaxhighlight>


===UNIX Platform===
===UNIX Platform===
Line 655: Line 678:
:'''Note:''' The '''<tt>address command</tt>''' clause causes the contents of the literal string that follows it to be sent to the command shell.
:'''Note:''' The '''<tt>address command</tt>''' 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>
<syntaxhighlight lang="oorexx">address command 'hostname -f'</syntaxhighlight>


<lang ooRexx>address command "echo $HOSTNAME"</lang>
<syntaxhighlight lang="oorexx">address command "echo $HOSTNAME"</syntaxhighlight>


Command output can also be captured by the program to allow further processing.
Command output can also be captured by the program to allow further processing.
Line 663: Line 686:
In the following examples output written to STDOUT/STDERR is piped into '''<tt>rxqueue</tt>''' which sends it in turn to a Rexx queue for further processing by the program:
In the following examples output written to STDOUT/STDERR is piped into '''<tt>rxqueue</tt>''' which sends it in turn to a Rexx queue for further processing by the program:


<lang ooRexx>/* Rexx */
<syntaxhighlight lang="oorexx">/* Rexx */
address command "echo $HOSTNAME | rxqueue"
address command "echo $HOSTNAME | rxqueue"
address command "hostname -f | rxqueue"
address command "hostname -f | rxqueue"
Line 670: Line 693:
say q_~right(2)':' hn
say q_~right(2)':' hn
end q_
end q_
</syntaxhighlight>
</lang>


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


<lang ooRexx>/* Rexx */
<syntaxhighlight lang="oorexx">/* Rexx */
qq = .rexxqueue~new()
qq = .rexxqueue~new()
address command "echo $HOSTNAME | rxqueue"
address command "echo $HOSTNAME | rxqueue"
Line 682: Line 705:
say q_~right(2)':' hn
say q_~right(2)':' hn
end q_
end q_
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>{System.showInfo {OS.getHostByName 'localhost'}.name}</lang>
<syntaxhighlight lang="oz">{System.showInfo {OS.getHostByName 'localhost'}.name}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Running the <code>hostname</code> or <code>uname</code> program and capturing its output (the first line of output) in a string.
Running the <code>hostname</code> or <code>uname</code> program and capturing its output (the first line of output) in a string.


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


=={{header|Pascal}}==
=={{header|Pascal}}==
For Windows systems see the [[Hostname#Delphi | Delphi]] example.
For Windows systems see the [[Hostname#Delphi | Delphi]] example.
On Unix systems, FreePascal has the function GetHostName:
On Unix systems, FreePascal has the function GetHostName:
<lang pascal>Program HostName;
<syntaxhighlight lang="pascal">Program HostName;


uses
uses
Line 703: Line 726:
begin
begin
writeln('The name of this computer is: ', GetHostName);
writeln('The name of this computer is: ', GetHostName);
end.</lang>
end.</syntaxhighlight>
Output example on Mac OS X:
Output example on Mac OS X:
<pre>
<pre>
Line 713: Line 736:


{{libheader|Sys::Hostname}}
{{libheader|Sys::Hostname}}
<lang perl>use Sys::Hostname;
<syntaxhighlight lang="perl">use Sys::Hostname;


$name = hostname;</lang>
$name = hostname;</syntaxhighlight>
=={{header|Perl 6}}==
<lang perl6>my $host = qx[hostname];</lang>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>constant tmp = "hostname.txt",
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (system_exec, file i/o)</span>
cmd = iff(platform()=WINDOWS?"hostname":"uname -n")
<span style="color: #008080;">constant</span> <span style="color: #000000;">tmp</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"hostname.txt"</span><span style="color: #0000FF;">,</span>
{} = system_exec(sprintf("%s > %s",{cmd,tmp}),4)
<span style="color: #000000;">cmd</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">WINDOWS</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"hostname"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"uname -n"</span><span style="color: #0000FF;">)</span>
string host = trim(get_text(tmp))
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">system_exec</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%s &gt; %s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">}),</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
{} = delete_file("hostname.txt")
<span style="color: #004080;">string</span> <span style="color: #000000;">host</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">))</span>
?host</lang>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">delete_file</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"hostname.txt"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">host</span>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 732: Line 756:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>echo $_SERVER['HTTP_HOST'];</lang>
<syntaxhighlight lang="php">echo $_SERVER['HTTP_HOST'];</syntaxhighlight>


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


{{works with|PHP|5.3+}}
{{works with|PHP|5.3+}}
<lang php>echo gethostname();</lang>
<syntaxhighlight lang="php">echo gethostname();</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
This will just print the hostname:
This will just print the hostname:
<lang PicoLisp>(call 'hostname)</lang>
<syntaxhighlight lang="picolisp">(call 'hostname)</syntaxhighlight>
To use it as a string in a program:
To use it as a string in a program:
<lang PicoLisp>(in '(hostname) (line T))</lang>
<syntaxhighlight lang="picolisp">(in '(hostname) (line T))</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>import System;
<syntaxhighlight lang="pike">import System;


int main(){
int main(){
write(gethostname() + "\n");
write(gethostname() + "\n");
}</lang>
}</syntaxhighlight>


=={{header|PL/SQL}}==
=={{header|PL/SQL}}==
<lang plsql>SET serveroutput on
<syntaxhighlight lang="plsql">SET serveroutput on
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);
DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);
END;</lang>
END;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>lvars host = sys_host_name();</lang>
<syntaxhighlight lang="pop11">lvars host = sys_host_name();</syntaxhighlight>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
This retreives the localhost's name:
This retreives the localhost's name:


<lang powerbasic>HOST NAME TO hostname$</lang>
<syntaxhighlight lang="powerbasic">HOST NAME TO hostname$</syntaxhighlight>


This attempts to retreive the name of an arbitrary machine on the network (assuming ipAddress& is valid):
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>
<syntaxhighlight lang="powerbasic">HOST NAME ipAddress& TO hostname$</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Windows systems have the <code>ComputerName</code> environment variable which can be used:
Windows systems have the <code>ComputerName</code> environment variable which can be used:
<lang powershell>$Env:COMPUTERNAME</lang>
<syntaxhighlight lang="powershell">$Env:COMPUTERNAME</syntaxhighlight>
Also PowerShell can use .NET classes and methods:
Also PowerShell can use .NET classes and methods:
<lang powershell>[Net.Dns]::GetHostName()</lang>
<syntaxhighlight lang="powershell">[Net.Dns]::GetHostName()</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{works with|PureBasic|4.41}}
{{works with|PureBasic|4.41}}
<lang PureBasic>InitNetwork()
<syntaxhighlight lang="purebasic">InitNetwork()
answer$=Hostname()</lang>
answer$=Hostname()</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.5}}
{{works with|Python|2.5}}
<lang python>import socket
<syntaxhighlight lang="python">import socket
host = socket.gethostname()</lang>
host = socket.gethostname()</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
Sys.info provides information about the platform that R is running on. The following code returns the hostname as a string.
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>
<syntaxhighlight lang="r">Sys.info()[["nodename"]]</syntaxhighlight>
Note that Sys.info isn't guaranteed to be available on all platforms. As an alternative, you can call an OS command.
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>
<syntaxhighlight lang="r">system("hostname", intern = TRUE)</syntaxhighlight>
... or retrieve an environment variable
... or retrieve an environment variable
<syntaxhighlight lang="r">
<lang R>
env_var <- ifelse(.Platform$OS.type == "windows", "COMPUTERNAME", "HOSTNAME")
env_var <- ifelse(.Platform$OS.type == "windows", "COMPUTERNAME", "HOSTNAME")
Sys.getenv(env_var)
Sys.getenv(env_var)
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket/base
#lang racket/base
(require mzlib/os)
(require racket/os)
(gethostname)
(gethostname)
</syntaxhighlight>
</lang>

=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my $host = qx[hostname];</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>print system/network/host</lang>
<syntaxhighlight lang="rebol">print system/network/host</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 812: Line 840:
<br>Other names could be used for the 3rd argument.
<br>Other names could be used for the 3rd argument.
<br><br>The &nbsp; ''computername'' &nbsp; is the same as the output for the &nbsp; '''hostname.exe''' &nbsp; program.
<br><br>The &nbsp; ''computername'' &nbsp; is the same as the output for the &nbsp; '''hostname.exe''' &nbsp; program.
<lang REXX>say value('COMPUTERNAME',,"ENVIRONMENT")
<syntaxhighlight lang="rexx">say value('COMPUTERNAME',,"ENVIRONMENT")
say value('OS',,"ENVIRONMENT")</lang>
say value('OS',,"ENVIRONMENT")</syntaxhighlight>
'''output''' (using Windows/XP)
'''output''' (using Windows/XP)
<pre>
<pre>
Line 822: Line 850:
This REXX solution is for R4 and ROO under the Microsoft NT family of Windows (XP, Vista, 7, etc).
This REXX solution is for R4 and ROO under the Microsoft NT family of Windows (XP, Vista, 7, etc).
<br>Other names could be used for the 3rd argument.
<br>Other names could be used for the 3rd argument.
<lang REXX>say value('COMPUTERNAME',,"SYSTEM")
<syntaxhighlight lang="rexx">say value('COMPUTERNAME',,"SYSTEM")
say value('OS',,"SYSTEM")</lang>
say value('OS',,"SYSTEM")</syntaxhighlight>


===MS DOS (without Windows), userid===
===MS DOS (without Windows), userid===
Under Microsoft DOS (with no Windows), the closest thing to a name of a host would be the 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>
<syntaxhighlight lang="rexx">say userid()</syntaxhighlight>


===MS DOS (without Windows), version of DOS===
===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.
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>
<syntaxhighlight lang="rexx">'VER' /*this passes the VER command to the MS DOS system. */</syntaxhighlight>
Each REXX interpreter has their own name (some have multiple names) for the environmental variables.
Each REXX interpreter has their own name (some have multiple names) for the environmental variables.
<br>Different operating systems may call their hostnames by different identifiers.
<br>Different operating systems may call their hostnames by different identifiers.
Line 841: Line 869:
This solution is platform specific and uses features that are available to the Regina implementation of Rexx.
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.
:Tested with Regina on Mac OS X. Should work on other UNIX/Linux distros.
<lang REXX>/* Rexx */
<syntaxhighlight lang="rexx">/* Rexx */
address command "hostname -f" with output stem hn.
address command "hostname -f" with output stem hn.
do q_ = 1 to hn.0
do q_ = 1 to hn.0
say hn.q_
say hn.q_
end q_
end q_
exit</lang>
exit</syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require 'socket'
<syntaxhighlight lang="ruby">require 'socket'
host = Socket.gethostname</lang>
host = Socket.gethostname</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>print Platform$ ' OS where Run BASIC is being hosted
<syntaxhighlight lang="runbasic">print Platform$ ' OS where Run BASIC is being hosted
print UserInfo$ ' Information about the user's web browser
print UserInfo$ ' Information about the user's web browser
print UserAddress$ ' IP address of the user</lang>
print UserAddress$ ' IP address of the user</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Works on windows and linux with crate <code>hostname</code> version 0.1.5
Works on windows and linux with crate <code>hostname</code> version 0.1.5
<lang Rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
match hostname::get_hostname() {
match hostname::get_hostname() {
Some(host) => println!("hostname: {}", host),
Some(host) => println!("hostname: {}", host),
None => eprintln!("Could not get hostname!"),
None => eprintln!("Could not get hostname!"),
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>println(java.net.InetAddress.getLocalHost.getHostName)</lang>
<syntaxhighlight lang="scala">println(java.net.InetAddress.getLocalHost.getHostName)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
{{works with|Chicken Scheme}}
<lang scheme>(use posix)
<syntaxhighlight lang="scheme">(use posix)
(get-host-name)</lang>
(get-host-name)</syntaxhighlight>
{{works with|Guile}}
{{works with|Guile}}
<lang scheme>(gethostname)</lang>
<syntaxhighlight lang="scheme">(gethostname)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 881: Line 909:
which returns the hostname.
which returns the hostname.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "socket.s7i";
include "socket.s7i";


Line 887: Line 915:
begin
begin
writeln(getHostname);
writeln(getHostname);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var sys = frequire('Sys::Hostname');
<syntaxhighlight lang="ruby">var sys = frequire('Sys::Hostname');
var host = sys.hostname;</lang>
var host = sys.hostname;</syntaxhighlight>
Or:
Or:
<lang ruby>var host = `hostname`.chomp;</lang>
<syntaxhighlight lang="ruby">var host = `hostname`.chomp;</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>Platform current nodeName</lang>
<syntaxhighlight lang="slate">Platform current nodeName</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|Slope}}==
<syntaxhighlight lang="slope">(hostname)</syntaxhighlight>
<lang snobol4>
output = host(4,"HOSTNAME")
end</lang>

=={{header|Standard ML}}==
<lang sml>NetHostDB.getHostName ()</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang Smalltalk>OperatingSystem getHostName</lang>
<syntaxhighlight lang="smalltalk">OperatingSystem getHostName</syntaxhighlight>

=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4">
output = host(4,"HOSTNAME")
end</syntaxhighlight>


=={{header|SQL}}==
=={{header|SQL}}==
{{works with|Oracle}}
{{works with|Oracle}}
<lang sql>
<syntaxhighlight lang="sql">
select host_name from v$instance;
select host_name from v$instance;
</syntaxhighlight>
</lang>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
<lang sql pl>
<syntaxhighlight lang="sql pl">
SELECT HOST_NAME FROM SYSIBMADM.ENV_SYS_INFO
SELECT HOST_NAME FROM SYSIBMADM.ENV_SYS_INFO
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 930: Line 958:


</pre>
</pre>

=={{header|Standard ML}}==
<syntaxhighlight lang="sml">NetHostDB.getHostName ()</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Swift 3
Swift 3
<lang Swift>print(ProcessInfo.processInfo.hostName)</lang>
<syntaxhighlight lang="swift">print(ProcessInfo.processInfo.hostName)</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
The basic introspection tool in TCL is the <tt>info</tt> 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:
The basic introspection tool in TCL is the <tt>info</tt> 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>
<syntaxhighlight lang="tcl">set hname [info hostname]</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
<lang toka>2 import gethostname
<syntaxhighlight lang="toka">2 import gethostname
1024 chars is-array foo
1024 chars is-array foo
foo 1024 gethostname
foo 1024 gethostname
foo type</lang>
foo type</syntaxhighlight>

=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
host=HOST ()
host=HOST ()
</syntaxhighlight>
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>hostname</lang>
<syntaxhighlight lang="bash">hostname</syntaxhighlight>
or
or
<lang bash>uname -n</lang>
<syntaxhighlight lang="bash">uname -n</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>out (ursa.net.localhost.name) endl console</lang>
<syntaxhighlight lang="ursa">out (ursa.net.localhost.name) endl console</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
The user-defined hostname function ignores its argument and returns a string.
The user-defined hostname function ignores its argument and returns a string.
<lang Ursala>#import cli
<syntaxhighlight lang="ursala">#import cli


hostname = ~&hmh+ (ask bash)/<>+ <'hostname'>!</lang>
hostname = ~&hmh+ (ask bash)/<>+ <'hostname'>!</syntaxhighlight>
For example, the following function returns the square root of its argument
For example, the following function returns the square root of its argument
if it's running on host kremvax, but otherwise returns the square.
if it's running on host kremvax, but otherwise returns the square.
<lang Ursala>#import flo
<syntaxhighlight lang="ursala">#import flo


creative_accounting = (hostname== 'kremvax')?(sqrt,sqr)</lang>
creative_accounting = (hostname== 'kremvax')?(sqrt,sqr)</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set objNetwork = CreateObject("WScript.Network")
Set objNetwork = CreateObject("WScript.Network")
WScript.Echo objNetwork.ComputerName
WScript.Echo objNetwork.ComputerName
</syntaxhighlight>
</lang>


=={{header|Vim Script}}==
=={{header|Vim Script}}==
<lang vim>echo hostname()</lang>
<syntaxhighlight lang="vim">echo hostname()</syntaxhighlight>


=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
Line 985: Line 1,017:
{{works with|VBA|6.5}}
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
{{works with|VBA|7.1}}
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Private Declare Function GetComputerName Lib "kernel32.dll" Alias "GetComputerNameW" _
Private Declare Function GetComputerName Lib "kernel32.dll" Alias "GetComputerNameW" _
Line 1,005: Line 1,037:
Sub Main()
Sub Main()
Debug.Assert Hostname() = Environ$("COMPUTERNAME")
Debug.Assert Hostname() = Environ$("COMPUTERNAME")
End Sub</lang>
End Sub</syntaxhighlight>

=={{header|V (Vlang)}}==
In Vlang, the "main()" entry point and declaration can be skipped in one file programs and when used like a script.
<syntaxhighlight lang="v (vlang)">import os

println(os.hostname())</syntaxhighlight>

=={{header|Wren}}==
Wren CLI doesn't currently expose a way to find the host name.

However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to get it for us.

<syntaxhighlight lang="wren">/* Hostname.wren */
class Host {
foreign static name() // the code for this is provided by Go
}

System.print(Host.name())</syntaxhighlight>

which we embed in the following Go program and run it.
{{libheader|WrenGo}}
<syntaxhighlight lang="go">/* Hostname.go */
package main

import (
wren "github.com/crazyinfin8/WrenGo"
"os"
)

type any = interface{}

func hostname(vm *wren.VM, parameters []any) (any, error) {
name, _ := os.Hostname()
return name, nil
}

func main() {
vm := wren.NewVM()
fileName := "Hostname.wren"
methodMap := wren.MethodMap{"static name()": hostname}
classMap := wren.ClassMap{"Host": wren.NewClass(nil, nil, methodMap)}
module := wren.NewModule(classMap)
vm.SetModule(fileName, module)
vm.InterpretFile(fileName)
vm.Free()
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>System.hostname</lang>
<syntaxhighlight lang="zkl">System.hostname</syntaxhighlight>
Or open a server socket, which contains the hostname.
Or open a server socket, which contains the hostname.
<lang zkl>Network.TCPServerSocket.open(8080).hostname</lang>
<syntaxhighlight lang="zkl">Network.TCPServerSocket.open(8080).hostname</syntaxhighlight>





Latest revision as of 21:04, 9 December 2023

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

with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Sockets;

procedure Demo is
begin
   Put_Line (GNAT.Sockets.Host_Name);
end Demo;

Aikido

println (System.hostname)

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

AppleScript

host name of (system info)

Arc

(system "hostname -f")

Arturo

print sys\hostname
Output:
drkameleons-Mac.home

AutoHotkey

MsgBox % A_ComputerName

via Windows Management Instrumentation (WMI)

for objItem in ComObjGet("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_ComputerSystem")
    MsgBox, % "Hostname:`t" objItem.Name

AWK

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

BaCon

PRINT "Hostname: ", HOSTNAME$

Batch File

Since Windows 2000 :

Hostname

BBC BASIC

      INSTALL @lib$+"SOCKLIB"
      PROC_initsockets
      PRINT "hostname: " FN_gethostname
      PROC_exitsockets

C/C++

Works with: gcc version 4.0.1
Works with: POSIX version .1
#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;
}

C#

System.Net.Dns.GetHostName();

Caché ObjectScript

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

Clojure

(.. java.net.InetAddress getLocalHost getHostName)
java -cp clojure.jar clojure.main -e "(.. java.net.InetAddress getLocalHost getHostName)"

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.

CoffeeScript

os = require 'os'
console.log os.hostname()

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 ()
    #+(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"))
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"

Crystal

hostname = System.hostname

D

import std.stdio, std.socket;

void main() {
    writeln(Socket.hostName());
}

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.

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.

Emacs Lisp

(system-name)

Erlang

Host = net_adm:localhost().

F#

printfn "%s" (System.Net.Dns.GetHostName())

Factor

USE: io.sockets
host-name

Forth

Works with: GNU Forth version 0.7.0
include unix/socket.fs

hostname type

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

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

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

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

friendly interactive shell

Translation of: UNIX Shell
hostname

or

uname -n

Frink

callJava["java.net.InetAddress", "getLocalHost"].getHostName[]


FutureBasic

include "NSLog.incl"
NSLog( @"%@", fn ProcessInfoHostName )
HandleEvents


Gambas

Click this link to run this code

Public Sub Main()

Print System.Host

End

Output:

charlie

Go

Use os.Hostname.

package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println(os.Hostname())
}

Groovy

println InetAddress.localHost.hostName

Harbour

? NetName()

Haskell

Library: network
import Network.BSD
main = do hostName <- getHostName
          putStrLn hostName

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


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

Icon and Unicon

procedure main()
  write(&host)
end

IDL

hostname = GETENV('computername')

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'

Java

import java.net.InetAddress;
import java.net.UnknownHostException;
void printHostname() throws UnknownHostException {
    InetAddress localhost = InetAddress.getLocalHost();
    System.out.println(localhost.getHostName());
}
penguin

JavaScript

Works with: JScript
var network = new ActiveXObject('WScript.Network');
var hostname = network.computerName;
WScript.echo(hostname);

jq

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]'
Output:
[
  "mini.local",
  "mini.local"
]

Jsish

var hn = exec("hostname", {retAll:true}).data.trim();

Julia

println(gethostname())
Output:
harlan

K

_h
Output:
`"narasimman-pc"

Kotlin

// version 1.1.4

import java.net.InetAddress

fun main(args: Array<String>) {
    println(InetAddress.getLocalHost().hostName)
}

Lasso

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

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

-> mymachine.local

LFE

(net_adm:localhost)

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$

Limbo

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

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";
}

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

Lingo

Library: Shell Xtra
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

LiveCode

answer the hostName

Lua

Requires: LuaSocket

socket = require "socket"
print( socket.dns.gethostname() )

M2000 Interpreter

Module Host {
      \\ one way
      Print computer$
      \\ second way
      Declare objNetwork "WScript.Network"
      With objNetwork,  "ComputerName" as cName$
      Print cName$, cName$=Computer$
      Declare objNetwork Nothing
}
Host

Maple

Sockets:-GetHostName()

Mathematica / Wolfram Language

$MachineName

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

mIRC Scripting Language

echo -ag $host

Modula-3

MODULE Hostname EXPORTS Main;

IMPORT IO, OSConfig;

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

MUMPS

Write $Piece($System,":")

NetRexx

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

say InetAddress.getLocalHost.getHostName

NewLISP

(! "hostname")

Nim

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

import nativesockets
echo getHostName()

Oberon-2

Works with oo2c version 2

MODULE HostName;
IMPORT 
  OS:ProcessParameters,
  Out;
BEGIN
  Out.Object("Host: " + ProcessParameters.GetEnv("HOSTNAME"));Out.Ln
END HostName.

Output:

Host: localhost.localdomain

Objeck

use Net;

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

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.

OCaml

Unix.gethostname()

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

ooRexx

These solutions are platform specific.

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

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_

Oz

{System.showInfo {OS.getHostByName 'localhost'}.name}

PARI/GP

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

str = externstr("hostname")[1];
str = externstr("uname -n")[1];

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

Perl

Works with: Perl version 5.8.6
use Sys::Hostname;

$name = hostname;

Phix

without js -- (system_exec, file i/o)
constant tmp = "hostname.txt",
         cmd = iff(platform()=WINDOWS?"hostname":"uname -n")
{} = system_exec(sprintf("%s > %s",{cmd,tmp}),4)
string host = trim(get_text(tmp))
{} = delete_file("hostname.txt")
?host
Output:
"Pete-PC"

PHP

echo $_SERVER['HTTP_HOST'];
echo php_uname('n');
Works with: PHP version 5.3+
echo gethostname();

PicoLisp

This will just print the hostname:

(call 'hostname)

To use it as a string in a program:

(in '(hostname) (line T))

Pike

import System;

int main(){
   write(gethostname() + "\n");
}

PL/SQL

SET serveroutput on
BEGIN
  DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);  
END;

Pop11

lvars host = sys_host_name();

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$

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

PureBasic

Works with: PureBasic version 4.41
InitNetwork()
answer$=Hostname()

Python

Works with: Python version 2.5
import socket
host = socket.gethostname()

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)

Racket

#lang racket/base
(require racket/os)
(gethostname)

Raku

(formerly Perl 6)

my $host = qx[hostname];

REBOL

print system/network/host

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.

say value('COMPUTERNAME',,"ENVIRONMENT")
say value('OS',,"ENVIRONMENT")

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.

say value('COMPUTERNAME',,"SYSTEM")
say value('OS',,"SYSTEM")

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

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.

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

Ruby

require 'socket'
host = Socket.gethostname

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

Rust

Works on windows and linux with crate hostname version 0.1.5

fn main() {
    match hostname::get_hostname() {
        Some(host) => println!("hostname: {}", host),
        None => eprintln!("Could not get hostname!"),
    }
}

Scala

println(java.net.InetAddress.getLocalHost.getHostName)

Scheme

Works with: Chicken Scheme
(use posix)
(get-host-name)
Works with: Guile
(gethostname)

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;

Sidef

var sys = frequire('Sys::Hostname');
var host = sys.hostname;

Or:

var host = `hostname`.chomp;

Slate

Platform current nodeName

Slope

(hostname)

Smalltalk

Works with: Smalltalk/X
OperatingSystem getHostName

SNOBOL4

      output = host(4,"HOSTNAME")
end

SQL

Works with: Oracle
select host_name from v$instance;

SQL PL

Works with: Db2 LUW
SELECT HOST_NAME FROM SYSIBMADM.ENV_SYS_INFO

Output:

HOST_NAME                                                                                                                                                                                                                                                      
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
hostname                                                                                                                                                                                                                                                          

  1 record(s) selected.

Standard ML

NetHostDB.getHostName ()

Swift

Swift 3

print(ProcessInfo.processInfo.hostName)

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]

Toka

2 import gethostname
1024 chars is-array foo
foo 1024 gethostname
foo type

TUSCRIPT

$$ MODE TUSCRIPT
host=HOST ()

UNIX Shell

hostname

or

uname -n

Ursa

out (ursa.net.localhost.name) endl console

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)

VBScript

Set objNetwork = CreateObject("WScript.Network")
WScript.Echo objNetwork.ComputerName

Vim Script

echo hostname()

Visual Basic

Works with: Visual Basic version 5
Works with: Visual Basic version 6
Works with: VBA version Access 97
Works with: VBA version 6.5
Works with: VBA version 7.1
Option Explicit

Private 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 = 31
Private Const NO_ERR As Long = 0

Private Function Hostname() As String
Dim 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 Function

Sub Main()
  Debug.Assert Hostname() = Environ$("COMPUTERNAME")
End Sub

V (Vlang)

In Vlang, the "main()" entry point and declaration can be skipped in one file programs and when used like a script.

import os

println(os.hostname())

Wren

Wren CLI doesn't currently expose a way to find the host name.

However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to get it for us.

/* Hostname.wren */
class Host {
    foreign static name() // the code for this is provided by Go
}

System.print(Host.name())

which we embed in the following Go program and run it.

Library: WrenGo
/* Hostname.go */
package main

import (
    wren "github.com/crazyinfin8/WrenGo"
    "os"
)

type any = interface{}

func hostname(vm *wren.VM, parameters []any) (any, error) {
    name, _ := os.Hostname()
    return name, nil
}

func main() {
    vm := wren.NewVM()
    fileName := "Hostname.wren"
    methodMap := wren.MethodMap{"static name()": hostname}
    classMap := wren.ClassMap{"Host": wren.NewClass(nil, nil, methodMap)}
    module := wren.NewModule(classMap)
    vm.SetModule(fileName, module)
    vm.InterpretFile(fileName)
    vm.Free()
}

zkl

System.hostname

Or open a server socket, which contains the hostname.

Network.TCPServerSocket.open(8080).hostname