linux 解析出函数名,linux下的域名解析函数

一、函数原型

#include

struct hostent *gethostbyname(const char *name);

作用:可以用于解析域名

结构体 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 */

}

示例:

#include

#include

#include

#include

#include

int main(int argc, char **argv)

{

if (argc != 2) {

fprintf(stderr, "Usage: %s hostname/n",

argv[1]);

exit(1);

}

struct hostent *answer;

int i;

char ipstr[16];

answer = gethostbyname(argv[1]);

if (answer == NULL) {

herror("gethostbyname"); //由gethostbyname自带的错误处理函数

exit(1);

}

for (i = 0; (answer->h_addr_list)[i] != NULL; i++) {

inet_ntop(AF_INET, (answer->h_addr_list)[i], ipstr, 16);

printf("%s/n", ipstr);

printf("officail name : %s/n", answer->h_name);

}

exit(0);

}

编译执行效果:

root@ubuntu:/media/2-G/教师代码/20100427/inet_v4/stream# ./myhost www.hpu.edu.cn

202.102.253.254

officail name : www.hpu.edu.cn

二、函数原型

int getaddrinfo(const char *node, const char *service,const struct addrinfo *hints,struct addrinfo **res);

此函数用链表存储数据。

char *node 一般是域名

const char *service //服务,可以为NULL

const  struct addrinfo *hints //指向由res返回的socket address的结构体

struct addrinfo **res //指向返回的结果

示例: #include #include #include #include #include #include int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s hostname/n", argv[1]); exit(1);    } struct addrinfo *answer, hint, *curr; char ipstr[16];    bzero(&hint, sizeof(hint)); hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; int ret = getaddrinfo(argv[1], NULL, &hint, &answer); if (ret != 0) { fprintf(stderr,"getaddrinfo: &s/n", gai_strerror(ret)); exit(1); } for (curr = answer; curr != NULL; curr = curr->ai_next) { inet_ntop(AF_INET, &(((struct sockaddr_in *)(curr->ai_addr))->sin_addr), ipstr, 16); printf("%s/n", ipstr); } freeaddrinfo(answer); exit(0); } 执行的结果类似于gethostbyname.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值