In a C project (POSIX), how do I get the fully qualified name for the current system?
For example, I can get just the hostname of my machine by doing
gethostname()
from unistd.h. This might give me machine3
in return, but I'm actually looking for machine3.somedomain.com
for example.
How do I go about getting this information? I do not want to use a call to system() to do this, if possible.
I believe you are looking for:
gethostbyaddress
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
The easy way, try uname()
If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()
The h_name of hostent{} should be your FQDN
To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.
The easiest way to do this is by first getting the local hostname using
uname()
orgethostname()
and then performing a lookup withgethostbyname()
and looking at theh_name
member of the struct it returns. If you are using ANSI c, you must useuname()
instead ofgethostname()
.Example:
Unfortunately,
gethostbyname()
is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would usegetaddrinfo()
.Example:
Of course, this will only work if the machine has a FQDN to give - if not, the result of the
getaddrinfo()
ends up being the same as the unqualified hostname.My solution:
gethostname()
is POSIX way to get local host name. Check outman
.BSD function
getdomainname()
can give you domain name so you can build fully qualified hostname. There is no POSIX way to get a domain I'm afraid.