linux网络编程——域名转换 gethostbyname与gethostbyaddr

域名转换

#include <netdb.h>
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 <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>

int main(void)
{
	struct hostent* hent;
	int i = 0;
	char addr[16];
    // 通过域名获取IP信息
	hent = gethostbyname("www.baidu.com");
	printf("h_name: %s\n", hent->h_name);

	while (hent->h_aliases[i] != NULL)
		printf("aliase: %s\n", hent->h_aliases[i++]);

	i = 0;
	while (hent->h_addr_list[i] != NULL)
		printf("ip addr %s\n", inet_ntop(hent->h_addrtype,hent->h_addr_list[i++], addr, sizeof(addr)));

	return 0;
}

还有一个类似的函数 gethostbyaddr,通过ip地址获取到规范名,别名等信息


#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
 
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:%s\n", strerror(errno));
		return -1;
	}
 
	phost = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);
	if (phost == NULL) {
		printf("gethostbyaddr error:%s\n", strerror(h_errno));
		return -1;
	}	
 
	printf("host name:%s\n", phost->h_name);
 
	return 0;
}


posted @ 2018-11-20 14:08  煮茗  阅读(275)  评论(0编辑  收藏  举报