零、介绍
1、作用
用域名或者主机名获取地址,操作系统提供的库函数。
域名系统(Domain Name System,DNS)主要用于主机名字与 IP 地址之间的映射。每个组织机构往往运行一个或多个名字服务器(name server),我们编写的客户端和服务器等应用程序通过调用解析器(resolver)的函数库中的函数接触 DNS 服务器。常见的解析器函数是 gethostbyname 和 gethostbyaddr,下图展示了应用进程、解析器和名字服务器之间的一个典型关系。

一、函数原型
GETHOSTBYNAME(3) Linux Programmer's Manual GETHOSTBYNAME(3)
NAME
gethostbyname, gethostbyaddr, sethostent, gethostent, endhostent,
h_errno, herror, hstrerror, gethostbyaddr_r, gethostbyname2, gethostby‐
name2_r, gethostbyname_r, gethostent_r - get network host entry
SYNOPSIS
#include <netdb.h>
extern int h_errno;
struct hostent *gethostbyname(const char *name);
#include <sys/socket.h> /* for AF_INET */
const char *hstrerror(int err);
二、返回值
失败返回 NULL 指针,成功返回的非空指针指向如下的 hostent 结构:
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 */
}

hostent->h_name
表示的是主机的规范名。例如 www.baidu.com 的规范名其实是 www.a.shifen.com 。
hostent->h_aliases
表示的是主机的别名。www.baidu.com 就是 baidu 他自己的别名。
hostent->h_addrtype
表示的是主机 ip 地址的类型。只会是 ipv4(AF_INET), 这个函数处理不了 ipv6 。
hostent->h_length
表示的是主机 ip 地址的长度。
hostent->h_addr_list
表示的是主机的 ip 地址。是网络字节序,需要通过 inet_ntop 函数转换。
三、栗子
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
extern int h_errno;
int main(int argc, char **argv)
{
if (argc != 2) {
printf("Use example: %s www.google.com\n", *argv);
return -1;
}
char *name = argv[1];
struct hostent *hptr;
hptr = gethostbyname(name);
if (hptr == NULL) {
printf("gethostbyname error for host: %s: %s\n", name, hstrerror(h_errno));
return -1;
}
//输出主机的规范名
printf("\tofficial: %s\n", hptr->h_name);
//输出主机的别名
char **pptr;
char str[INET_ADDRSTRLEN];
for (pptr = hptr->h_aliases; *pptr != NULL; pptr++) {
printf("\ttalias: %s\n", *pptr);
}
//输出ip地址
switch (hptr->h_addrtype) {
case AF_INET:
pptr = hptr->h_addr_list;
for (; *pptr != NULL; pptr++) {
printf("\taddress: %s\n",
inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)));
}
break;
default:
printf("unknown address type\n");
break;
}
return 0;
}
gcc -o main main.c
./main www.baidu.com
结果
official: www.a.shifen.com
talias: www.baidu.com
address: 220.181.38.150
address: 220.181.38.150
(SAW:Game Over!)
本文详细介绍了DNS系统的作用,以及在Linux环境中使用gethostbyname函数进行域名到IP地址转换的过程。通过示例代码展示了如何获取主机的规范名、别名及IP地址,并解释了相关结构体字段的含义。
1952

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



