域名转换
#include
struct hostent *gethostbyname(const char *name);
参数: name: 执行主机名的指针
返回值: 返回一个hostent指针
struct hostent
{
char *h_name; // 表示主机的规范名
char **h_aliases; // 表示主机的别名,别名可能有多个
int h_addrtype; // 表示的是主机ip地址的类型, ipv4 AF_iNET 或 ipv6 AFINET6
int h_length; // 表示主机ip地址的长度
char ** h_addr_list; // 表示的是主机的ip地址
}
#include
#include
#include
int main(void)
{
struct hostent* hent;
int i = 0;
char addr[16];
// 通过域名获取IP信息
hent = gethostbyname("www.baidu.com");
printf("h_name: %sn", hent->h_name);
while (hent->h_aliases[i] != NULL)
printf("aliase: %sn", hent->h_aliases[i++]);
i = 0;
while (hent->h_addr_list[i] != NULL)
printf("ip addr %sn", inet_ntop(hent->h_addrtype,hent->h_addr_list[i++], addr, sizeof(addr)));
return 0;
}
还有一个类似的函数 gethostbyaddr,通过ip地址获取到规范名,别名等信息
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
struct in_addr addr;
struct hostent *phost;
if (inet_pton(AF_INET, argv[1], &addr) <= 0) {
printf("inet_pton error:%sn", strerror(errno));
return -1;
}
phost = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);
if (phost == NULL) {
printf("gethostbyaddr error:%sn", strerror(h_errno));
return -1;
}
printf("host name:%sn", phost->h_name);
return 0;
}
内容来源于网络如有侵权请私信删除