Hostname: Difference between revisions
mNo edit summary |
|||
Line 302: | Line 302: | ||
<lang octave>uname().nodename</lang> |
<lang octave>uname().nodename</lang> |
||
=={{header|ooRexx}}== |
|||
A solution using ActiveX/OLE on Windows |
|||
<lang ooRexx>say .oleObject~new('WScript.Network')~computerName</lang> |
|||
and one using the Windows environment variables |
|||
<lang ooRexx>say value('COMPUTERNAME',,'environment')</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
Revision as of 19:57, 15 June 2012
You are encouraged to solve this task according to the task description, using any language you may know.
Find the name of the host on which the routine is running.
Ada
Works with GCC/GNAT <lang ada>with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets;
procedure Demo is begin
Put_Line (GNAT.Sockets.Host_Name);
end Demo;</lang>
ALGOL 68
<lang algol68>STRING hostname; get(read OF execve child pipe("/bin/hostname","hostname",""), hostname); print(("hostname: ", hostname, new line))</lang>
Aikido
<lang aikido> println (System.hostname) </lang>
AutoHotkey
<lang AutoHotkey>MsgBox % A_ComputerName</lang>
AWK
<lang awk>$ awk 'BEGIN{print ENVIRON["HOST"]}' E51A08ZD</lang>
BBC BASIC
<lang bbcbasic> INSTALL @lib$+"SOCKLIB"
PROC_initsockets PRINT "hostname: " FN_gethostname PROC_exitsockets</lang>
C/C++
<lang c>#include <stdlib.h>
- include <stdio.h>
- include <limits.h>
- include <unistd.h>
int main(void) {
char name[_POSIX_HOST_NAME_MAX + 1]; return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}</lang>
C#
<lang csharp>System.Net.Dns.GetHostName();</lang>
Clojure
<lang clojure> (.. java.net.InetAddress getLocalHost getHostName) </lang>
<lang shell> java -cp clojure.jar clojure.main -e "(.. java.net.InetAddress getLocalHost getHostName)" </lang>
CoffeeScript
<lang coffeescript> os = require 'os' console.log os.hostname() </lang>
Common Lisp
Another operating system feature that is implemented differently across lisp implementations. Here we show how to create a function that obtains the required result portably by working differently for each supported implementation. This technique is heavily used to make portable lisp libraries. <lang lisp>(defun get-host-name ()
#+sbcl (machine-instance) #+clisp (let ((s (machine-instance))) (subseq s 0 (position #\Space s))) #-(or sbcl clisp) (error "get-host-name not implemented"))</lang>
Another way is to use the FFI to access POSIX' gethostname(2)
:
<lang lisp>(cffi:defcfun ("gethostname" c-gethostname) :int
(buf :pointer) (len :unsigned-long))
(defun get-hostname ()
(cffi:with-foreign-object (buf :char 256) (unless (zerop (c-gethostname buf 256)) (error "Can't get hostname")) (values (cffi:foreign-string-to-lisp buf))))</lang>
<lang lisp>BOA> (get-hostname) "aurora"</lang>
D
<lang d>import std.stdio; import std.socket;
void main() {
writefln("%s", Socket.hostName());
}</lang>
Delphi
<lang Delphi>program ShowHostName;
{$APPTYPE CONSOLE}
uses Windows;
var
lHostName: array[0..255] of char; lBufferSize: DWORD;
begin
lBufferSize := 256; if GetComputerName(lHostName, lBufferSize) then Writeln(lHostName) else Writeln('error getting host name');
end.</lang>
E
<lang e>makeCommand("hostname")()[0].trim()</lang>
Not exactly a good way to do it. A better way ought to be introduced along with a proper socket interface.
Factor
<lang factor>host-name</lang>
Forth
<lang forth>include unix/socket.fs
hostname type</lang>
Erlang
<lang Erlang>Host = net_adm:localhost().</lang>
Fortran
The function/subroutine HOSTNM is a GNU extension. <lang fortran>program HostTest
character(len=128) :: name call hostnm(name) print *, name
end program HostTest</lang>
Go
<lang go>package main
import ( "fmt" "os" )
func main() { host, _ := os.Hostname() fmt.Printf("hostname: %s\n", host) }</lang>
Groovy
<lang groovy>println InetAddress.localHost.hostName</lang>
Haskell
<lang haskell>import Network.BSD main = do hostName <- getHostName
putStrLn hostName</lang>
Icon and Unicon
<lang icon>procedure main()
write(&host)
end</lang>
IDL
<lang idl>hostname = GETENV('computername')</lang>
J
<lang j>NB. Load the socket libraries
load 'socket' coinsert 'jsocket'
NB. fetch and implicitly display the hostname
> {: sdgethostname
NB. If fetching the hostname is the only reason for loading the socket libraries, NB. and the hostname is fetched only once, then use a 'one-liner' to accomplish it:
> {: sdgethostname coinsert 'jsocket' [ load 'socket'</lang>
Java
<lang java>import java.net.*; class DiscoverHostName {
public static void main(final String[] args) { try { System.out.println(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { // Doesn't actually happen, but Java requires it be handled. } }
}</lang>
JavaScript
<lang javascript>var network = new ActiveXObject('WScript.Network'); var hostname = network.computerName; WScript.echo(hostname);</lang>
Lua
Requires: LuaSocket <lang lua>socket = require "socket" print( socket.dns.gethostname() )</lang>
Liberty BASIC
<lang lb>lpBuffer$=Space$(128) + Chr$(0) struct SIZE,sz As Long SIZE.sz.struct=Len(lpBuffer$)
calldll #kernel32, "GetComputerNameA",lpBuffer$ as ptr, SIZE as struct, result as Long CurrentComputerName$=Trim$(Left$(lpBuffer$, SIZE.sz.struct))
print CurrentComputerName$</lang>
Mathematica
<lang Mathematica>$MachineName</lang>
MATLAB
This is a built-in MATLAB function. "failed" is a Boolean which will be false if the command sent to the OS succeeds. "hostname" is a string containing the system's hostname, provided that the external command hostname exists.
<lang Matlab>[failed,hostname] = system('hostname')</lang>
Modula-3
<lang modula3>MODULE Hostname EXPORTS Main;
IMPORT IO, OSConfig;
BEGIN
IO.Put(OSConfig.HostName() & "\n");
END Hostname.</lang>
MUMPS
<lang MUMPS> Write $System </lang>
The output varies by implementation. The following is an example of Intersystem's Caché 5.2.0.329.0:
USER>Write $SYSTEM STORMSTATION:CACHE520
The portion before the colon is the machine running Caché, and the portion after the colon is the instance.
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols binary
say InetAddress.getLocalHost.getHostName </lang>
NewLISP
<lang NewLISP>(! "hostname")</lang>
Objective-C
Cocoa / Cocoa Touch / GNUstep:
<lang objc> NSLog(@"%@", [[NSProcessInfo processInfo] hostName]); </lang>
Example Output:
<lang objc> 2010-09-16 16:20:00.000 Playground[1319:a0f] sierra117.local // Hostname is sierra117.local. </lang>
Objeck
<lang objeck> use Net;
bundle Default {
class Hello { function : Main(args : String[]) ~ Nil { TCPSocket->HostName()->PrintLine(); } }
} </lang>
OCaml
<lang ocaml>Unix.gethostname()</lang>
Octave
Similarly to MATLAB, we could call system command hostname to know the hostname. But we can also call the internal function uname() which returns a structure holding several informations, among these the hostname (nodename):
<lang octave>uname().nodename</lang>
ooRexx
A solution using ActiveX/OLE on Windows
<lang ooRexx>say .oleObject~new('WScript.Network')~computerName</lang>
and one using the Windows environment variables
<lang ooRexx>say value('COMPUTERNAME',,'environment')</lang>
Oz
<lang oz>{System.showInfo {OS.getHostByName 'localhost'}.name}</lang>
Pascal
For Windows systems see the Delphi example. On Unix systems, FreePascal has the function GetHostName: <lang pascal>Program HostName;
uses
unix;
begin
writeln('The name of this computer is: ', GetHostName);
end.</lang> Output example on Mac OS X:
The name of this computer is: MyComputer.local
Perl
<lang perl>use Sys::Hostname;
$name = hostname;</lang>
PHP
<lang php>echo $_SERVER['HTTP_HOST'];</lang>
<lang php>echo php_uname('n');</lang>
<lang php>echo gethostname();</lang>
PicoLisp
This will just print the hostname: <lang PicoLisp>(call 'hostname)</lang> To use it as a string in a program: <lang PicoLisp>(in '(hostname) (line T))</lang>
Pike
<lang pike>import System;
int main(){
write(gethostname() + "\n");
}</lang>
PL/SQL
<lang plsql>SET serveroutput on BEGIN
DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);
END;</lang>
Pop11
<lang pop11>lvars host = sys_host_name();</lang>
PowerBASIC
This retreives the localhost's name:
<lang powerbasic>HOST NAME TO hostname$</lang>
This attempts to retreive the name of an arbitrary machine on the network (assuming ipAddress& is valid):
<lang powerbasic>HOST NAME ipAddress& TO hostname$</lang>
PowerShell
Windows systems have the ComputerName
environment variable which can be used:
<lang powershell>$Env:COMPUTERNAME</lang>
Also PowerShell can use .NET classes and methods:
<lang powershell>[Net.Dns]::GetHostName()</lang>
PureBasic
<lang PureBasic>InitNetwork() answer$=Hostname()</lang>
Python
<lang python>import socket host = socket.gethostname()</lang>
R
Sys.info provides information about the platform that R is running on. The following code returns the hostname as a string. <lang R>Sys.info()"nodename"</lang> Note that Sys.info isn't guaranteed to be available on all platforms. As an alternative, you can call an OS command. <lang R>system("hostname", intern = TRUE)</lang> ... or retrieve an environment variable <lang R> env_var <- ifelse(.Platform$OS.type == "windows", "COMPUTERNAME", "HOSTNAME") Sys.getenv(env_var) </lang>
REBOL
<lang REBOL>print system/network/host</lang>
REXX
<lang rexx> say userid() </lang>
Ruby
<lang ruby>require 'socket' host = Socket.gethostname</lang>
Run BASIC
<lang runbasic>print Platform$ ' OS where Run BASIC is being hosted print UserInfo$ ' Information about the user's web browser print UserAddress$ ' IP address of the user</lang>
Scala
<lang scala>println(java.net.InetAddress.getLocalHost.getHostName)</lang>
Scheme
<lang scheme>(use posix) (get-host-name)</lang>
<lang scheme>(gethostname)</lang>
Seed7
The library socket.s7i defines the function getHostname, which returns the hostname.
<lang seed7>$ include "seed7_05.s7i";
include "socket.s7i";
const proc: main is func
begin writeln(getHostname); end func;</lang>
Slate
<lang slate>Platform current nodeName</lang>
SNOBOL4
<lang snobol4>
output = host(4,"HOSTNAME")
end</lang>
Standard ML
<lang sml>NetHostDB.getHostName ()</lang>
Tcl
The basic introspection tool in TCL is the info command. It can be used to find out about the version of the current Tcl or Tk, the available commands and libraries, variables, functions, the level of recursive interpreter invocation, and, amongst a myriad other things, the name of the current machine:
<lang Tcl>set hname [info hostname]</lang>
Toka
<lang toka>2 import gethostname 1024 chars is-array foo foo 1024 gethostname foo type</lang>
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT SET host=HOST () </lang>
UNIX Shell
<lang bash>hostname</lang> or <lang bash>uname -n</lang>
Ursala
The user-defined hostname function ignores its argument and returns a string. <lang Ursala>#import cli
hostname = ~&hmh+ (ask bash)/<>+ <'hostname'>!</lang> For example, the following function returns the square root of its argument if it's running on host kremvax, but otherwise returns the square. <lang Ursala>#import flo
creative_accounting = (hostname== 'kremvax')?(sqrt,sqr)</lang>
- Programming Tasks
- Programming environment operations
- Networking and Web Interaction
- Ada
- ALGOL 68
- Aikido
- AutoHotkey
- AWK
- BBC BASIC
- C
- C++
- C sharp
- Clojure
- CoffeeScript
- Common Lisp
- CFFI
- D
- Delphi
- E
- E examples needing attention
- Factor
- Forth
- Erlang
- Fortran
- Go
- Groovy
- Haskell
- Network
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Lua
- Liberty BASIC
- Mathematica
- MATLAB
- Modula-3
- MUMPS
- NetRexx
- NewLISP
- Objective-C
- Objeck
- OCaml
- Octave
- OoRexx
- Oz
- Pascal
- Perl
- PHP
- PicoLisp
- Pike
- PL/SQL
- Pop11
- PowerBASIC
- PowerShell
- PureBasic
- Python
- R
- REBOL
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Seed7
- Slate
- SNOBOL4
- Standard ML
- Tcl
- Toka
- TUSCRIPT
- UNIX Shell
- Ursala
- ACL2/Omit
- Locomotive Basic/Omit
- ML/I/Omit
- PARI/GP/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- Unlambda/Omit
- ZX Spectrum Basic/Omit