Linux系统提供了系统调用,可以查询到设备的域名信息
在头文件netdb.h
中,提供了两个系统调用gethostbyaddr
和gethostbyname
#include <netdb.h>
struct hostent *gethostbyname(const char*name);
struct hostent *gethostbyaddr(const char *addr, int len, 0);
// 调用结果成功,则返回非空指针;错误则返回空指针,且同时设置h_errno。
其中返回的结构struct hostent
用于记录主机信息条目具体为
/* Description of data base entry for a single host. */
struct hostent
{
char *h_name; /* Official name of host. */
char **h_aliases; /* Alias list. */
int h_addrtype; /* Host address type. */
int h_length; /* Length of address. */
char **h_addr_list; /* List of addresses from name server. */
#ifdef __USE_MISC
# define h_addr h_addr_list[0] /* Address, for backward compatibility.*/
#endif
};
下面是一个简单的示例,用于说明这两个系统调用的使用方法
#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <string.h>
void process_print_res(const struct hostent *res)
{
std::cout << "official name: " <<res->h_name <<std::endl;
for(char **p = res->h_aliases; *p!=nullptr; ++p){
std::cout <<"alias names: " <<*p <<std::endl;
}
std::cout << "addr net type: ";
switch (res->h_addrtype)
{
case AF_INET:
std::cout << "ipv4";
break;
case AF_INET6:
std::cout << "ipv6";
break;
default:
std::cout << "unknown";
break;
}
std::cout <<std::endl;
for(char **p = res->h_addr_list; *p!=nullptr; ++p){
struct in_addr tmp;
tmp.s_addr = ((struct in_addr *)*p)->s_addr;
char *addr = inet_ntoa(tmp);
std::cout <<"address: " <<addr <<std::endl;
}
}
int main(int argc, char *argv[]) {
struct in_addr addr;
struct hostent *p_host;
if(argc != 2){
std::cout <<"usage: " <<argv[0] << " <domain_name or ip>" <<std::endl;
return 0;
}
if(0 != inet_aton(argv[1], &addr)){
// input is a address
p_host = gethostbyaddr((const void*)&addr, sizeof(addr), AF_INET);
if(!p_host){
std::cout<<"get host by addr err" <<std::endl;
return 0;
}
} else {
// input is a hostname
p_host = gethostbyname(argv[1]);
if(!p_host){
std::cout<<"get host by name err" <<std::endl;
}
}
process_print_res(p_host);
return 0;
}