您的位置:首页 > 理论基础 > 计算机网络

Linux 网络编程之通过IP或者主机名获取信息

2015-06-15 23:02 911 查看
struct hostent
{
char *h_name; /* 主机的正式名称*/
char **h_aliases; /* 主机的别名列表*/
int h_addrtype; /* 主机的地址类型AF_INET */
int h_length; /* 主机的地址长度*/
char **h_addr_list; /* 主机的IP地址列表*/
}
#define h_addr h_addr_list[0] /* 主机的第一个IP地址*/


struct hostent *gethostbyname(const char *name);

通过主机名 name 获取 主机IP等信息。成功返回给定主机名包含的主机名字和地址信息的 hostent结构体指针。


示例如下:
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Usage: %s domain_name \n",argv[0]);
exit(EXIT_FAILURE);
}

struct hostent *ht = gethostbyname(argv[1]);
if( ht )
{
int i = 0;
printf("Source domain: %s \n", argv[1]);
printf("Formal domain: %s \n", ht->h_name);
printf("Address type: %s \n", \
ht->h_addrtype == AF_INET ? "AF_INET" : "AF_INET6" );
printf("Address length:%d \n", ht->h_length);

for( ; ; ++i)
{
if (ht->h_aliases[i])
printf("Aliases name %d : %s \n",i+1 ,ht->h_aliases[i]);
else
break;
}

for(i=0; ; ++i)
{
if (ht->h_addr_list[i])
printf("IP Address %d : %s \n",i+1, \
inet_ntoa((unsigned int *)ht->h_addr_list[i]));
else
break;
}

}

return 0;
}


struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type);

返回对应于给定地址的包含主机名字和地址信息的hostent结构指针。

addr 指向网络字节序地址的指针。

len 地址的长度。

type 地址类型。



示例如下:
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>

#define ADDR_LEN 	4
#define ADDR_TYPE	AF_INET

int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s IP Address\n",argv[0]);
exit(EXIT_FAILURE);
}

struct in_addr *addr = (struct in_addr *)malloc(sizeof(struct in_addr));
if ( ! inet_aton(argv[1], addr))
{
printf(" %s Invalid address",argv[1]);
exit(EXIT_FAILURE);
}

struct hostent *ht = gethostbyaddr(addr, ADDR_LEN, ADDR_TYPE);

if(ht)
{
int i = 0;
printf("Source IP: %s\n",argv[1]);
printf("Formal domain: %s \n",ht->h_name);
printf("Address type: %s\n",ht->h_addrtype == AF_INET ? "AF_INET" : "AF_INET6");
printf("Address length: %d \n", ht->h_length);

for( ; ; ++i)
{
if(ht->h_aliases[i])
printf("Aliases name %d : %s\n",i+1,ht->h_aliases[i]);
else
break;
}

for(i = 0; ; ++i)
{
if(ht->h_addr_list[i])
printf("IP Address %d : %s\n",i+1, \
inet_ntoa((unsigned int *)ht->h_addr_list[i]));
else
break;
}
}
else
{
switch(h_errno)
{
case HOST_NOT_FOUND :
printf("The specified host is unknown\n");
break;

case NO_ADDRESS:
printf("The requested name is valid but does not have an IP address.\n");
break;

case NO_RECOVERY:
printf(" A nonrecoverable name server error occurred.\n");
break;

case TRY_AGAIN:
printf("A temporary error occurred in the authoritative \
domain name server. Please try again later.\n");
break;
}
}

return 0;
}


gethostbyname()和gethostbyaddr()函数功能返回的HOSTENT的结构或NULL指针。

如果出现错误。h_errno的变量保存的错误号。

错误的可变h_errno的可以具有以下值:

HOST_NOT_FOUND

指定的主机是未知的。

NO_ADDRESS或NO_DATA

请求的名称是有效的,但没有一个IP地址。

NO_RECOVERY

不可恢复的名称服务器发生错误。

TRY_AGAIN

一个临时错误发生在权威域名服务器。请稍后再试。

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