域名
DNS 是对IP地址和域名进行相互转换的系统,其核心是 DNS 服务器
1 什么是域名
域名就是我们常常在地址栏里面输入的地址,将比较难记忆的IP地址变成人类容易理解的信息。
通过:ping 域名
or nslookup 域名
都可以得知域名解析的ip地址
nslookup
server 可以知道默认的dns服务器地址配置
1.1 DNS服务器
相当于一个字典,可以查询出某一个域名对应的IP地址
域名服务器查询地址的过程:
先向上询问上级的域名服务器,如果也不知道就一直往上走到根服务器
根服务器知道所在dns服务器路线再往下查直到找到目标为止。在返回到原主机。
2 IP与域名的转换
2.1 程序用到域名的意义
一个域名可以绑定多个ip,ip时常在变,且不方便记忆通过域名可随时更改解析,方便使用。
2.2 利用域名获取ip地址
可通过以下函数进行获取
#include <netdb.h>
struct hostent * gethostbyname(const char * hostname); //通过域名获取ip地址 失败返回NULL指针
struct hostent {
char *h_name; //official name 官方域名
char **h_aliases; //alias list 用来获得其他域名。一个ip可以绑定多个域名
int h_addrtype; //host address type 支持IPv4和6 通过此变量获取h_addr_list 的ip地址的和地址族信息,若是IPv4 存有AF_INET
int h_length; // address length 地址长度
char ** h_addr_list; // address list 通过整数形式保存域名对应的ip
}
具体实现代码和过程如下:
- [gethostbyname.c]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char *argv[]) {
struct hostent *host;
host = gethostbyname(argv[1]);
if (!host)
error("gethost ... error");
printf("Official name: %s \n", host->h_name);
for (int 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 (int 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;
}
如图显示了我的域名和www.naver.com 域名的ip地址等信息。
其中
inet_ntoa(*(struct in_addr*) addr)//这个函数是之前所讲的网络字节序转字符串
2.3利用ip获取域名
可通过以下函数获取
#include <netdb.h>
struct hostent *gethostbyaddr(const char * addr, socklen_t len, int family);
失败返回NULL指针
addr 是包含ip信息的in_addr结构体指针
len 字节数 IPv4 4 IPv6 16
family 地址族信息
过程与代码如下:
- [gethostbyaddr.c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char *argv[]) {
int i;
struct hostent *host;
struct sockaddr_in addr;
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("gethost ... error");
printf("Official name: %s \n", host->h_name);
for (int 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 (int 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;
}