9

I'm currently hacking on an elisp IRC bot and have a section of code that I want to enable only when it's run on a remote machine with a specific hostname. However, I couldn't find any premade function to retrieve the machine's hostname. Eventually I settled for (shell-command-to-string "uname -n"), but this feels wrong and will certainly not work on other operating systems. Is there anything better suited for this task?

Drew
  • 75,699
  • 9
  • 109
  • 225
wasamasa
  • 21,803
  • 1
  • 65
  • 97

2 Answers2

15

C-hf system-name

system-name is a built-in function in ‘C source code’.

(system-name)

Return the host name of the machine you are running on, as a string.

It's also a variable, but (a) that's now deprecated, and (b) the function pre-dates it, so don't use the variable. It is safe and best to use the function in all scenarios.

C-hv system-name

system-name is a variable defined in ‘C source code’.
Its value is "foo"

  This variable is obsolete since 25.1;
  use (system-name) instead

Documentation:
The host name of the machine Emacs is running on.
phils
  • 48,657
  • 3
  • 76
  • 115
0

Here is the command I used, copied from https://github.com/redguardtoo/find-and-ctags/blob/master/find-and-ctags.el#L110,

(defun find-and-ctags-get-hostname ()
  "Reliable way to get current hostname.
`(getenv \"HOSTNAME\")' won't work because $HOSTNAME is NOT an
 environment variable.
`system-name' won't work because /etc/hosts could be modified"
  (with-temp-buffer
    (shell-command "hostname" t)
    (goto-char (point-max))
    (delete-char -1)
(buffer-string)))
Tobias
  • 32,569
  • 1
  • 34
  • 75
chen bin
  • 4,781
  • 18
  • 36
  • @phils does not use `system-name`. He uses `(system-name)`. Does this circumvent the difficulties with modifications of `/etc/hosts`? – Tobias Jun 23 '17 at 13:21
  • The variable is set by the function, so any issue with one would affect both. I'm not sure of the need for this custom code. On my system at least `hostname(1)` uses `gethostname(2)` to establish a value, which is also what `system-name` (or more specifically `init_system_name`) uses (when it is available; if `gethostname` is not available then `uname(2)` is used instead). I don't know whether the method used by `system-name` has changed over the years, though; nor whether `hostname` behaves differently on other systems. – phils Jun 23 '17 at 14:39
  • @Tobias I don't know `(system-name)`. The code was written four years ago when I was using Emacs 24.3. – chen bin Jun 24 '17 at 03:31
  • I've just tried it. I modified the hostname of my computer with `hostname XYZ`. Afterwards `(system-name)` returned `XYZ` instead of the old hostname from `/etc/hostname`. Therefore `(system-name)` is the way to go. – Tobias Jun 24 '17 at 10:10
  • (system-name) returns the FQDN. What's the way to get the first token (eg 'www' when (system-name) returns 'www.foo.com')? – Peter Flynn May 29 '18 at 07:43