50

I know I can use platform.node() to get my computer's network name:

>>> import platform
>>> platform.node()
'MyComputerName'

But what I really want is something that will work similar to the following:

>>> get_full_network_domain_name()
'MyComputerName.it.na.mycompany.com'

Does something like this exist?

Jace Browning
  • 11,699
  • 10
  • 66
  • 90

1 Answers1

69

The fully qualified domain name is returned by socket.getfqdn().

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    Thanks, "fully qualified domain name" was the phrase I was looking for! – Jace Browning Jul 20 '12 at 13:12
  • 10
    For me this doesn't yield the same result as `hostname -f` on the shell. So be careful. – Daniël van Eeden Jan 02 '14 at 08:22
  • @DaniëlvanEeden , do you know what is the situation it does not return the same as in `hostname -f`? – semente Jul 11 '14 at 13:52
  • 20
    @semente , `hostname -f` does it like this: `socket.getaddrinfo(socket.gethostname(), 0, flags=socket.AI_CANONNAME)[0][3]` and `getfqdn()` seems to lookup the hostname in /etc/hosts and uses the first entry which contains a dot. For me the `hostname -f` returns 'daniel-thinkpad' and `getfqdn()` returns localhost6.localdomain6 – Daniël van Eeden Jul 24 '14 at 20:12
  • 4
    @DaniëlvanEeden: Thanks! However, my version of `getaddrinfo` doesn't support keyword arguments, so I had to use `socket.getaddrinfo(socket.gethostname(), 0, 0, 0, 0, socket.AI_CANONNAME)[0][3]` instead. – Florian Brucker Nov 30 '16 at 11:10
  • 1
    This does not work reliably at all. Half the time it comes back with just the hostname when I see that the hostname it comes back with is easily looked up by nslookup and comes back with an fqdn. – Nathan McKaskle May 10 '19 at 20:32
  • A scenario I'm running into gives an incorrect result with either option (`getfqdn()` or the more elaborate function call from @DaniëlvanEeden). My scenario is when I have my Windows 10 "work" laptop, connected to my home WiFi. The laptop's normal FQDN is along the lines of `laptopname.big.company.network.com`, and this is what both methods return. But on my home network, the laptop's actual working FQDN is just `laptopname.lan`. Neither of the commands above return this. – JDM Jun 30 '20 at 13:16