abcazx
abcazx

Reputation: 125

what's the difference between gethostname and getfqdn?

Just the title, what the difference between them? In python, socket.gethostbyname(socket.gethostname()) and socket.gethostbyname(socket.getfqdn()) return different results on my computer.

Upvotes: 8

Views: 13673

Answers (3)

ninjakang
ninjakang

Reputation: 295

Note that the selected reply above is quite confusing.

YES socket.getfqdn WILL return a full-qualified hostname. But if it's going to be 'localhost.localdomain' you probably actually want socket.gethostname instead so that you get something that is somewhat useable.

The difference is that one reads from /etc/hostname and /etc/domainname while the other reads the kernel nodename. Depending on your distribution, configuration, OS, etc. your mileage WILL vary.

What this means is that you generally want to first check socket.getfqdn, and verify if it returns 'localhost.localdomain'. if it does, use socket.gethostname instead.

Finally, python also has platform.node which is basically the same as socket.gethostname on python, though this might be a better choice for multiplatform code.

That's quite an important detail.

Upvotes: 5

Oleksii Kachaiev
Oleksii Kachaiev

Reputation: 6234

From documentation,

socket.gethostname returns a string containing the hostname of the machine where the Python interpreter is currently executing.

socket.getfqdn returns a fully qualified domain name if it's available or gethostname otherwise.

Fully qualified domain name is a domain name that specifies its exact location in the tree hierarchy of the DNS. From wikipedia examples:

For example, given a device with a local hostname myhost and a parent domain name example.com, the fully qualified domain name is myhost.example.com.

Upvotes: 7

Jon Taylor
Jon Taylor

Reputation: 7905

The hostname is not the fully qualified domain name, hence why they return different results.

getfqdn() will return the fully qualified domain name while gethostname() will return the hostname.

Upvotes: 0

Related Questions