1. compile
cc ns.c -lresolv -lsocket -lnsl
2. run
It will print out local node name and its full dsn name. (uname -n)
It DSN work failed, a error string will be printed out, and full dsn name will be same as nodename.
#include <string.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <netdb.h>
/**
* Compile how to:
* cc ns.c -lresolv -lsocket -lnsl
*/
void main(int argc, char * argv[])
{
static struct utsname n;
typedef union
{
HEADER hdr;
unsigned char buf[1024];
} querybuf;
querybuf answer;
unsigned char *cp;
long l;
char name[255];
char *ret_ptr;
if (uname(&n) == -1)
{
printf("Cannot run uname(...)/n");
return;
}
ret_ptr = n.nodename;
/*
* On certain machines (Solaris, for instance), n.nodename is not in FQDN
* format. On Linux it is. So, let's ensure that what we have is a
* FQDN
*/
l = res_init();
if (l == -1) {
printf("Cannot run res_init(...)/n");
goto done;
}
l = res_search(ret_ptr, C_IN, T_ANY, (u_char *)&answer, sizeof(answer));
if (l == -1 || (unsigned long)l < sizeof(HEADER)) {
printf("Cannot run res_search(...)/n");
goto done;
}
cp = (unsigned char *)&answer + sizeof(HEADER);
memset(name, 0, sizeof(name));
l = dn_expand((unsigned char *)&answer, (unsigned char *)&answer+512, cp, name, 255);
if (l == -1) {
printf("Cannot run dn_expand(...)/n");
goto done;
}
ret_ptr = name;
done:
if (l == -1)
printf("node name=[%s], fullname=[%s]/n",n.nodename,ret_ptr);
else
printf("node name=[%s], fullname=[%s]/n",n.nodename,ret_ptr);
ret_ptr = 0;
}
本文提供了一个C语言程序示例,演示了如何使用系统调用获取主机名及通过DNS查询获得主机的全域名。该程序首先利用uname()函数获取节点名称,然后使用res_init(), res_search()和dn_expand()等函数进行DNS查询,最终输出本地节点名称及其全域名。
619

被折叠的 条评论
为什么被折叠?



