12

I am trying to get the hostname in Python. In linux, if I type hostname on the command prompt I get

root@phxdbx45:/home/david/zkpython# hostname
phxdbx45

But if I type hostname -f then I get below full qualified hostname in ubuntu and that's what I need from Python as well.

root@phxdbx45:/home/david/zkpython# hostname -f
phxdbx45.phx.host.com

I know in Python we can use below code but it does not give me fully qualified host name. It gives me the output of hostname as I mentioned above.

#!/usr/bin/python

import socket

hostname = socket.gethostname()
print hostname

Is there any way to get fully qualified hostname in Python which is reliable and correct?

arsenal
  • 23,366
  • 85
  • 225
  • 331

1 Answers1

33

Use the descriptively-named function socket.getfqdn():

>>> import socket   
>>> socket.getfqdn()
'phxdbx45.phx.host.com'
  • 1
    That just gives me 'localhost' – xApple Apr 28 '17 at 09:10
  • 1
    I get the simple name of my machine, without the domain name, but it's the same as what `hostname -f` returns. However, `hostname --all-fqdns` returns the FQDN. – EM0 Jul 27 '17 at 17:03
  • This definitely depends on how the host OS was configured. as @xApple mentioned, it's possible to get only `localhost` . – András Aszódi Dec 16 '22 at 19:46