Windows XP Windows 7 Windows 2003 Windows Vista Windows教程綜合 Linux 系統教程
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟件教程
 Windows教程網 >> Linux系統教程 >> Linux教程 >> linux 下域名解析函數gethostbyname 和 getaddrinfo

linux 下域名解析函數gethostbyname 和 getaddrinfo

日期:2017/2/7 14:32:49      編輯:Linux教程
 

一、函數原型
#include <netdb.h>
struct hostent *gethostbyname(const char *name);
作用:可以用於解析域名
結構體 hostent 的原型如下:
struct hostent {
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
}
示例:
#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);
}

Copyright © Windows教程網 All Rights Reserved