如何在 C(主机名和域信息)中找到当前机器的完整主机名? [英] How do I find the current machine's full hostname in C (hostname and domain information)?

查看:41
本文介绍了如何在 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.

我该如何获取这些信息?如果可能,我不想使用对 system() 的调用来执行此操作.

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] = '';
gethostname(hostname, 1023);
printf("Hostname: %s
", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s
", h->h_name);

不幸的是,gethostbyname() 在当前的 POSIX 规范中已被弃用,因为它不能很好地与 IPv6 配合使用.此代码的更现代版本将使用 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] = '';
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
", gai_strerror(gai_result));
    exit(1);
}

for(p = info; p != NULL; p = p->ai_next) {
    printf("hostname: %s
", 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天全站免登陆