1. DNS (Domain Name System)是对IP地址和域名进行相互转换的系统,核心是DNS服务器。
所有计算机都记录着默认DNS服务器地址,通过这个DNS服务器得到相应域名的IP地址信息。
一般服务器域名不会轻易改变,但会相对频繁地改变服务器IP地址。可以通过ping www.baidu.com 查看对应的IP地址。
也可以通过nslookup命令查看计算机中注册的默认DNS服务器地址。
2. 计算机内置的默认DNS服务器并不知道网络中的所有域名IP地址,若本地不知道,则会询问其他DNS服务器。
3. IP地址与域名之间的转换
书中的一句名言:所有学习都要在开始前认识到其必要性!
利用域名获取IP地址
#include <netdb.h>
struct hostent * gethostbyname(const char * hostname);
成功时返回hostent结构体地址,失败返回NULL指针
struct hostent{
char * h_name; //official name 官方域名
char ** h_aliases; //alias list,其他域名
int h_addrtype; //host address type
int h_length; //address length
char ** h_addr_list //address list
}
4. 示例一,gethostbyname:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error_handling(char *message);
int main(int argc, char *argv[]){
int i;
struct hostent *host;
if(argc != 2){
printf("Usage : %s <addr> \n",argv[0]);
exit(1);
}
host = gethostbyname(argv[1]);
if(!host){
error_handling("gethostbyname error");
}
printf("Official name: %s \n",host->h_name);
for(i=0;host->h_aliases[i];i++){
printf("Aliases %d: %s \n",i+1,host->h_aliases[i]);
}
printf("Address type : %s \n",(host->h_addrtype == AF_INET)?"AF_INET":"AF_INET6");
for(i=0;host->h_addr_list[i];i++){
printf("IP addr %d:%s \n", i+1,inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
}
return 0;
}
void error_handling(char *message){
fputs(message,stderr);
fputs("\n",stderr);
exit(1);
}
运行结果:
alex@alex-virtual-machine:/extra/tcpip$ ./a.out www.baidu.com
Official name: www.a.shifen.com
Aliases 1: www.baidu.com
Address type : AF_INET
IP addr 1:180.97.33.108
IP addr 2:180.97.33.107
5. IP地址获取域名
#include <netdb.h>
struct hostent * gethostbyaddr(const char *addr, socklen_t len, int family);
成功时返回hostent结构体变量地址,失败返回NULL
addr:含有IP地址信息的in_addr结构体指针,为了兼容IPV4,IPV6
len:第一个参数字节数
family:地址簇,IPV4 AF_INET,IPV6 AF_INET6
程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
void error_handling(char *message);
int main(int argc, char *argv[]){
int i;
struct hostent *host;
struct sockaddr_in addr;
if(argc != 2){
printf("Usage : %s <addr> \n",argv[0]);
exit(1);
}
memset(&addr,0,sizeof(addr));
addr.sin_addr.s_addr = inet_addr(argv[1]);
host = gethostbyaddr((char *)&addr.sin_addr,4,AF_INET);
if(!host){
error_handling("gethostbyaddr error");
}
printf("Official name: %s \n",host->h_name);
for(i=0;host->h_aliases[i];i++){
printf("Aliases %d: %s \n",i+1,host->h_aliases[i]);
}
printf("Address type : %s \n",(host->h_addrtype == AF_INET)?"AF_INET":"AF_INET6");
for(i=0;host->h_addr_list[i];i++){
printf("IP addr %d:%s \n", i+1,inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
}
return 0;
}
void error_handling(char *message){
fputs(message,stderr);
fputs("\n",stderr);
exit(1);
}
执行结果:谷歌地址
alex@alex-virtual-machine:/extra/tcpip$ ./addr 93.46.8.89
Official name: 93-46-8-89.ip105.fastwebnet.it
Address type : AF_INET
IP addr 1:93.46.8.89