您的位置:首页 > 运维架构 > Linux

linux 通过Ip获取主机名等信息gethostbyaddr()等。

2013-03-06 10:52 555 查看
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
	char *ptr,**pptr;
	struct hostent *hptr;
	char str[32];
	char ipaddr[16];
	struct in_addr *hipaddr = (struct in_addr *)malloc(sizeof(struct in_addr));

	ptr = argv[1];
	printf("0:%s\n",ptr);
	if(!inet_aton(ptr,hipaddr))
	{
		printf("error1\n");
		return 1;
	}

	if( (hptr = gethostbyaddr(hipaddr,4,AF_INET) ) == NULL)
	{
		h_errno;
		printf("err2 %s\n",ptr);
		switch(h_errno)
		{
		case HOST_NOT_FOUND:printf("111\n");break;
//		case NO_ADDRESS:
//		case NO_DATA:printf("112\n");break;
		case NO_RECOVERY:printf("113\n");break;
		case TRY_AGAIN:printf("115\n");break;
		}
		return 1;
	}

	printf("hostname:%s\n",hptr->h_name);

	for(pptr = hptr->h_aliases; *pptr != NULL; pptr++ )
		printf("%s\n",*pptr);

	switch( hptr->h_addrtype)
	{
		case AF_INET:
		case AF_INET6:
		 	pptr = hptr->h_addr_list;
			for(;*pptr!=NULL;pptr++)
				printf("address:%s\n",inet_ntop(hptr->h_addrtype,*pptr,str,sizeof(str)));
			break;
		default:
			printf("default \n");
			break;
	}

	return 0;
}

/*
 * //http://www.rosoo.net/a/201105/11535.html
 *
返回值

的gethostbyname()和gethostbyaddr()函数功能返回的 HOSTENT的结构或NULL指针,如果出现错误。错误时,h_errno的变量保存的错误号。
错误的可变h_errno的可以具有以下值:
HOST_NOT_FOUND
指定的主机是未知的。
NO_ADDRESS或NO_DATA
请求的名称是有效的,但没有一个IP地址。
NO_RECOVERY
不可恢复的名称服务器发生错误。
TRY_AGAIN
一个临时错误发生在权威域名服务器。请稍后再试。
 * */



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: