我要如何找到在C(主机名和域名信息)目前该机的全名? [英] How do I find the current machine's full hostname in C (hostname and domain information)?

查看:216
本文介绍了我要如何找到在C(主机名和域名信息)目前该机的全名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个C项目(POSIX),我如何才能完全合格的名称为当前系统?

In a C project (POSIX), how do I get the fully qualified name for the current system?

例如,我可以做让我的机器只是主机名
的gethostname()从unistd.h中。这可能给我 machine3 的回报,但我确实在寻找 machine3.somedomain.com 例如

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.

推荐答案

要为机器获得一个完全合格的名字,我们必须先获得本地主机名,然后查找的规范名称。

To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.

要做到这一点,最简单的方法是先用的uname()获得本地主机名的gethostname()然后执行与查找的gethostbyname(),并看着它返回结构的 h_name 成员。如果您使用的是ANSI C,你的必须的使用的uname()而不是的gethostname()

The easiest way to do this is by first getting the local hostname using uname() or gethostname() and then performing a lookup with gethostbyname() and looking at the h_name member of the struct it returns. If you are using ANSI c, you must use uname() instead of gethostname().

例如:

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);

不幸的是,的gethostbyname()是在当前的POSIX规范pcated,因为它不使用IPv6发挥好德$ P $。这code的更现代版将使用的getaddrinfo()

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 use getaddrinfo().

例如:

struct addrinfo hints, *info, *p;
int gai_result;

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;

if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
    exit(1);
}

for(p = info; p != NULL; p = p->ai_next) {
    printf("hostname: %s\n", p->ai_canonname);
}

freeaddrinfo(info);

当然,如果机器有一个FQDN给这只会工作 - 如果不是,结果在的getaddrinfo()最终被同为不合格主机名。

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.

这篇关于我要如何找到在C(主机名和域名信息)目前该机的全名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆