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?

2 Answers 2


C-hf system-name

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


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

The host name of the machine Emacs is running on.

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"
    (shell-command "hostname" t)
    (goto-char (point-max))
    (delete-char -1)
  • @phils does not use system-name. He uses (system-name). Does this circumvent the difficulties with modifications of /etc/hosts?
    – Tobias
    Jun 23, 2017 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, 2017 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, 2017 at 3: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, 2017 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')? May 29, 2018 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.