Movatterモバイル変換


[0]ホーム

URL:


Jump to content
Rosetta Code
Search

Hostname

From Rosetta Code
Task
Hostname
You are encouraged tosolve 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

withAda.Text_IO;useAda.Text_IO;withGNAT.Sockets;procedureDemoisbeginPut_Line(GNAT.Sockets.Host_Name);endDemo;

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

hostnameof(system info)

Arc

(system "hostname -f")

Arturo

printsys\hostname
Output:
drkameleons-Mac.home

AutoHotkey

MsgBox%A_ComputerName

via Windows Management Instrumentation (WMI)

forobjIteminComObjGet("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

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

BBC BASIC

Works with:BBC BASIC for Windows
INSTALL@lib$+"SOCKLIB"PROC_initsocketsPRINT"hostname: "FN_gethostnamePROC_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>intmain(void){charname[_POSIX_HOST_NAME_MAX+1];returngethostname(name,sizeofname)==-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.InetAddressgetLocalHostgetHostName)
java-cpclojure.jarclojure.main-e"(.. java.net.InetAddress getLocalHost getHostName)"

COBOL

identificationdivision.program-id.hostname.datadivision.working-storagesection.01hostnamepic x(256).01nullpospic 999value1.proceduredivision.call"gethostname"usinghostnamebyvaluelengthofhostnamestringhostnamedelimitedbylow-valueintohostnamewithpointernullposdisplay"Host: "hostname(1:nullpos-1)goback.endprogramhostname.

CoffeeScript

os=require'os'console.logos.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.

(defunget-host-name()#+(orsbclccl)(machine-instance)#+clisp(let((s(machine-instance)))(subseqs0(position#\Spaces)))#-(orsbclcclclisp)(error"get-host-name not implemented"))
Library:CFFI

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"

Crystal

hostname=System.hostname

D

importstd.stdio,std.socket;voidmain(){writeln(Socket.hostName());}

Delphi

programShowHostName;{$APPTYPE CONSOLE}usesWindows;varlHostName:array[0..255]ofchar;lBufferSize:DWORD;beginlBufferSize:=256;ifGetComputerName(lHostName,lBufferSize)thenWriteln(lHostName)elseWriteln('error getting host name');end.

DuckDB

Works with:DuckDB version V1.1
Works with:DuckDB version V1.0

Retrieving the HOSTNAME environment variable

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     │└────────────────────┘

Importing the value of `hostname`

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

`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 │└────────────────┘

"Dynamic SQL"

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          │└─────────────────────────┘

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.socketshost-name

Forth

Works with:GNU Forth version 0.7.0
includeunix/socket.fshostnametype

Fortran

Works with:gfortran

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

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:DimAsStringhostnameOpenPipe"hostname"ForInputAs#1Input#1,hostnameClose#1PrinthostnamePrintPrint"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

PublicSubMain()PrintSystem.HostEnd

Output:

charlie

Go

Useos.Hostname.

packagemainimport("fmt""os")funcmain(){fmt.Println(os.Hostname())}

Groovy

printlnInetAddress.localHost.hostName

Harbour

? NetName()

Haskell

Library:network
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

Icon andUnicon

proceduremain()write(&host)end

IDL

hostname=GETENV('computername')

J

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'

Java

importjava.net.InetAddress;importjava.net.UnknownHostException;
voidprintHostname()throwsUnknownHostException{InetAddresslocalhost=InetAddress.getLocalHost();System.out.println(localhost.getHostName());}
penguin

JavaScript

Works with:JScript
varnetwork=newActiveXObject('WScript.Network');varhostname=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

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

Julia

println(gethostname())
Output:
harlan

K

_h
Output:
`"narasimman-pc"

Kotlin

// version 1.1.4importjava.net.InetAddressfunmain(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

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

LFE

(net_adm:localhost)

Liberty BASIC

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$

Limbo

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.

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 laterelse  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 commandhostname exists.

[failed,hostname]=system('hostname')

mIRC Scripting Language

echo -ag $host

Modula-3

MODULEHostnameEXPORTSMain;IMPORTIO,OSConfig;BEGINIO.Put(OSConfig.HostName()&"\n");ENDHostname.

MUMPS

Write $Piece($System,":")

NetRexx

/* NetRexx */optionsreplaceformatcommentsjavacrossrefsavelogsymbolsbinarysayInetAddress.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”:

importnativesocketsechogetHostName()

Oberon-2

Works with oo2c version 2

MODULEHostName;IMPORTOS:ProcessParameters,Out;BEGINOut.Object("Host: "+ProcessParameters.GetEnv("HOSTNAME"));Out.LnENDHostName.

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(@"%@",[[NSProcessInfoprocessInfo]hostName]);

Example Output:

2010-09-1616:20:00.000Playground[1319:a0f]sierra117.local// Hostname is sierra117.local.

OCaml

Unix.gethostname()

Octave

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

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

sayvalue('COMPUTERNAME',,'environment')

UNIX Platform

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.

Note: Theaddress command clause causes the contents of the literal string that follows it to be sent to the command shell.
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_

Oz

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

PARI/GP

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

Pascal

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

PascalABC.NET

##System.Net.Dns.GetHostName.Print


Perl

Works with:Perl version 5.8.6
Library:Sys::HostnameHostname
useSys::Hostname;$name=hostname;

Phix

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
Output:
"Pete-PC"

PHP

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

PicoLisp

This will just print the hostname:

(call 'hostname)

To use it as a string in a program:

(in '(hostname) (line T))

Pike

importSystem;intmain(){write(gethostname()+"\n");}

Pluto

os.execute("hostname > tmp")localhostname=io.contents("tmp"):rstrip()print($"Hostname is {hostname}")os.remove("tmp")

PL/SQL

SETserveroutputonBEGINDBMS_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 theComputerName 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
importsockethost=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

#langracket/base(requireracket/os)(gethostname)

Raku

(formerly Perl 6)

my$host =qx[hostname];

Rebol

printreaddns://

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.

sayvalue('COMPUTERNAME',,"ENVIRONMENT")sayvalue('OS',,"ENVIRONMENT")

output (using Windows/XP)

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

sayvalue('COMPUTERNAME',,"SYSTEM")sayvalue('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.

sayuserid()

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

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 */addresscommand"hostname -f"withoutputstemhn.doq_=1tohn.0sayhn.q_endq_exit

Ruby

require'socket'host=Socket.gethostname

Run BASIC

print Platform$    ' OS where Run BASIC is being hostedprint UserInfo$    ' Information about the user's web browserprint UserAddress$ ' IP address of the user

Rust

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!"),    }}

Scala

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

Scheme

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

Seed7

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;

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

Toka

2 import gethostname1024 chars is-array foofoo 1024 gethostnamefoo type

TUSCRIPT

$$ MODE TUSCRIPThost=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 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)

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 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 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 osprintln(os.hostname())

Wren

Library:Wren-std

Uses the 'os' sub-module.

import "os" for PlatformSystem.print(Platform.hostName)

zkl

System.hostname

Or open a server socket, which contains the hostname.

Network.TCPServerSocket.open(8080).hostname
Retrieved from "https://rosettacode.org/wiki/Hostname?oldid=392572"
Categories:
Hidden category:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

[8]ページ先頭

©2009-2026 Movatter.jp