#include <stdio.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
struct hostent *lh = gethostbyname("localhost");
if (lh)
puts(lh->h_name);
else
herror("gethostbyname");
return 0;
}
ホスト名を決定するための信頼性の高い方法ではありませんが、機能する場合があります。(何が返されるか/etc/hosts
は、設定方法によって異なります)。次のような行がある場合:
127.0.0.1 foobar localhost
...その後、「foobar」を返します。ただし、逆の場合も一般的ですが、「localhost」を返すだけです。より信頼性の高い方法は、次のgethostname()
関数を使用することです。
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
int main(int argc, char *argv[])
{
char hostname[HOST_NAME_MAX + 1];
hostname[HOST_NAME_MAX] = 0;
if (gethostname(hostname, HOST_NAME_MAX) == 0)
puts(hostname);
else
perror("gethostname");
return 0;
}