现在的位置: 首页 > 综合 > 正文

linux下的域名解析函数

2013年10月15日 ⁄ 综合 ⁄ 共 2003字 ⁄ 字号 评论关闭

 一直都对域名解析函数,没想到上网查资料时发现linux竟然提供了域名解析的函数,输入一个网址,立马可以得到ip,很是方便,而且还可以得到一个域名对应的多个ip以及域名的别名,特记之。

 http://blog.csdn.net/yalizhi123/article/details/5713155

一、函数原型
#include <netdb.h>
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 <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

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 <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
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.

抱歉!评论已关闭.