960

I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.

12 Answers 12

1457

Use socket and its gethostname() functionality. This will get the hostname of the computer where the Python interpreter is running:

import socket
print(socket.gethostname())
6
  • 109
    And note that for the FQDN you can use socket.getfqdn() Commented Feb 21, 2013 at 19:55
  • 25
    Just curious what's the difference between socket.gethostname() and os.uname()[1] or platform.uname()[1]
    – LetsOMG
    Commented Mar 23, 2018 at 21:52
  • 1
    is this portable? Commented Apr 26, 2018 at 2:01
  • how to get a hostname without DNS suffix?
    – iEfimoff
    Commented Jul 1, 2021 at 19:52
  • 1
    @iEfimoff On some systems (rhel 7. 9 x86_64) socket.gethostname still returns the full name with FQDN. I used sysName = socket.gethostname().split(".")[0] to get just the short hostname into a variable named 'sysName'
    – Chris
    Commented Jan 26, 2022 at 22:46
488

Both of these are pretty portable:

import platform
platform.node()

import socket
socket.gethostname()

Any solutions using the HOST or HOSTNAME environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.

8
  • 9
    Well, semi-portable. On some platforms, platform.node() gives the fqdn and on others, only the hostname
    – raindog308
    Commented Nov 16, 2014 at 4:31
  • 5
    python -m timeit "import socket; socket.gethostname()" 10000 loops, best of 3: 76.3 usec per loop Commented Feb 27, 2017 at 13:17
  • 21
    python -m timeit "import platform; platform.node()" 1000000 loops, best of 3: 0.74 usec per loop Commented Feb 27, 2017 at 13:17
  • 36
    @BelowtheRadar don't worry, I usually only call either of these once per script.
    – robert
    Commented Mar 1, 2017 at 11:58
  • 12
    platform.node() is even faster than os.getenv. gethostname isn't even a contender. But if time isn't a factor: import os, platform; os.getenv('HOSTNAME', os.getenv('COMPUTERNAME', platform.node())).split('.')[0] should be cross-platform and support environment variables if they exist - which permits some user control in exigent circumstances, eg HOSTNAME=correct python xyz.py Commented Apr 7, 2017 at 1:55
187

You will probably load the os module anyway, so another suggestion would be:

import os
myhost = os.uname()[1]
9
  • 15
    +1 for a solution using os module. Not portable and not really accurate, but handy anyway.
    – MestreLion
    Commented Jul 27, 2013 at 3:25
  • 45
    os.uname is not supported on Windows: docs.python.org/dev/library/os#os.uname
    – Noam Manos
    Commented Aug 26, 2014 at 12:22
  • 18
    You can also do os.uname().nodename to make it a bit more obvious in 3.3+
    – Hut8
    Commented May 10, 2015 at 18:21
  • 4
    An answer below gives the similar looking platform.uname()[1], which DOES work on Windows. Commented Sep 16, 2015 at 7:00
  • 11
    @fantabolous You probably shouldn't use positional words like "below" as answers may have shifted during landing ;) Commented Apr 5, 2016 at 10:46
80

What about :

import platform

h = platform.uname()[1]

Actually you may want to have a look to all the result in platform.uname()

3
  • 1
    Worked on Ubuntu and Windows for me. Thanks! 👍
    – GollyJer
    Commented Oct 3, 2018 at 21:10
  • 1
    platform.uname().node is a bit more verbose than platform.uname()[1], I assume it was introduced around the same time as the os.uname equivalent mentioned in another comment.
    – Luc
    Commented Dec 6, 2021 at 23:17
  • This should be the same as platform.node()
    – nurettin
    Commented Feb 10, 2022 at 16:34
65

os.getenv('HOSTNAME') and os.environ['HOSTNAME'] don't always work. In cron jobs and WSDL, HTTP HOSTNAME isn't set. Use this instead:

import socket
socket.gethostbyaddr(socket.gethostname())[0]

It always (even on Windows) returns a fully qualified host name, even if you defined a short alias in /etc/hosts.

If you defined an alias in /etc/hosts then socket.gethostname() will return the alias. platform.uname()[1] does the same thing.

I ran into a case where the above didn't work. This is what I'm using now:

import socket
if socket.gethostname().find('.')>=0:
    name=socket.gethostname()
else:
    name=socket.gethostbyaddr(socket.gethostname())[0]

It first calls gethostname to see if it returns something that looks like a host name, if not it uses my original solution.

2
  • 16
    you probably want socket.getfqdn(), though it is not what the OP asks
    – jfs
    Commented Jan 19, 2013 at 3:02
  • socket.gethostbyaddr(socket.gethostname()) on my machine (which is running FreeBSD) returns ('localhost', ['my-machine-name', 'my-machine-namelocaldomain'], ['::1']), so returning the first element just returns localhost. (Meanwhile, socket.gethostname() returns my-machine-name for me.)
    – jamesdlin
    Commented May 12, 2021 at 0:34
52

From at least python >= 3.3:

You can use the field nodename and avoid using array indexing:

os.uname().nodename

Although, even the documentation of os.uname suggests using socket.gethostname()

3
  • 2
    According to the doc, os.uname is available only on "recent flavors of Unix"
    – Pedru
    Commented Mar 9, 2021 at 12:16
  • @CharlesPlager Worked for me in Python 3.8.6, RHEL7 container running in OpenShift
    – diman82
    Commented Mar 20, 2021 at 19:54
  • Not portable, no windows support Commented Dec 29, 2022 at 14:36
25

If I'm correct, you're looking for the socket.gethostname function:

>> import socket
>> socket.gethostname()
'terminus'
17

You have to execute this line of code

sock_name = socket.gethostname()

And then you can use the name to find the addr :

print(socket.gethostbyname(sock_name))
1
  • this approach returns just ip for me
    – shmnff
    Commented Nov 29, 2023 at 4:26
14

socket.gethostname() could do

12

To get fully qualified hostname use socket.getfqdn()

import socket

print socket.getfqdn()
1
  • Yes, but unfortunately sometimes this just returns localhost, and not even the hostname as returned by socket.gethostname().
    – Asclepius
    Commented Nov 24, 2022 at 2:10
9

On some systems, the hostname is set in the environment. If that is the case for you, the os module can pull it out of the environment via os.getenv. For example, if HOSTNAME is the environment variable containing what you want, the following will get it:

import os
system_name = os.getenv('HOSTNAME')

Update: As noted in the comments, this doesn't always work, as not everyone's environment is set up this way. I believe that at the time I initially answered this I was using this solution as it was the first thing I'd found in a web search and it worked for me at the time. Due to the lack of portability I probably wouldn't use this now. However, I am leaving this answer for reference purposes. FWIW, it does eliminate the need for other imports if your environment has the system name and you are already importing the os module. Test it - if it doesn't work in all the environments in which you expect your program to operate, use one of the other solutions provided.

6
  • 6
    That returns "None" for me. According to the link you posted, that means the variable 'HOSTNAME' doesn't exist... :-/
    – John
    Commented Nov 24, 2010 at 22:16
  • @John: Are you on Windows? It worked for me on a Linux box, but I get None on Windows also.
    – GreenMatt
    Commented Nov 25, 2010 at 23:23
  • @MuhiaNJoroge: I think that depends on your implementation/installation. When I wrote that answer I was on a Red Hat box and it worked. Now I'm on Ubuntu and it doesn't work. I've modified the answer.
    – GreenMatt
    Commented Mar 6, 2014 at 19:11
  • Not work in lenovo NAS, return None. Now i'm using import socket print(socket.gethostname()) Commented Dec 15, 2015 at 4:48
  • @RuiMartins: As I said, it doesn't seem to work everywhere. Glad you found something that works.
    – GreenMatt
    Commented Dec 15, 2015 at 14:20
7

I needed the name of the PC to use in my PyLog conf file, and the socket library is not available, but os library is.

For Windows I used:

os.getenv('COMPUTERNAME', 'defaultValue')

Where defaultValue is a string to prevent None being returned

5
  • 19
    COMPUTERNAME is a very Microsoft only environment variable and therefor not portable. Commented Oct 5, 2015 at 16:34
  • 3
    Yes, but it does work for M.S. systems, and if it fits, it works. Many times people here get too entwined on speed or platform independence when practicality and the question render them irrelevant.
    – Bill Kidd
    Commented Oct 6, 2015 at 21:09
  • 12
    @BillKidd OP mentions Windows, OS X, and Linux in the question, so needing system portability is a very reasonable assumption.
    – zstewart
    Commented Nov 10, 2015 at 20:07
  • 1
    @BillKidd While in general it is true that you should avoid premature optimization or portability, not using a readily available and and arguably more maintainable solution because it is more portable is going to the opposite extreme. Commented Apr 1, 2016 at 19:08
  • 1
    socket.gethostname() is better than os.environ['COMPUTERNAME']. Because os.environ['COMPUTERNAME'] do not support long PC name after I used it.
    – kyc1109
    Commented Jun 16, 2021 at 16:18

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