用代码获得/etc/resolv.conf文件的最后修改时间和文件内信息
/etc/resolv.conf
文件是DNS域名解析的配置文件,每行以一个关键字开头,后接配置参数。resolv.conf的关键字主要有四个,分别是:
nameserver #定义DNS服务器的IP地址
domain #定义本地域名
search #定义域名的搜索列表
sortlist #对返回的域名进行排序
最主要是nameserver关键字,如果没指定nameserver就找不到DNS服务器,其它关键字是可选的。
我的ubuntu 12.04 resolv.conf文件如下:
[plain]
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.0.1
search www.google.com google.com
用代码获得/etc/resolv.conf文件的最后修改时间和文件内信息,如下:
[plain]
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define RESOLV_CONF_PATH "/etc/resolv.conf"
#define MAX_DNS_SERVERS 2
#define MAX_NET_STR_LEN 256
typedef struct dns_info_s {
char dns_svr[MAX_DNS_SERVERS][MAX_NET_STR_LEN];
char domain[MAX_NET_STR_LEN];
} dns_info_t;
time_t net_get_dns_info_mtime(void);
int net_get_dns_info(dns_info_t *dns_info);
time_t net_get_dns_info_mtime(void)
{
const char *file = RESOLV_CONF_PATH;
struct stat stat_buf;
if (stat(RESOLV_CONF_PATH, &stat_buf) < 0) {
if (errno == ENOENT)
printf("%s has been removed!/n", RESOLV_CONF_PATH);
else {
printf("stat(%s)/n", file);
return 0;
}
}
printf("%s: st_mtime=0x%08X/n", file, (int)stat_buf.st_mtime);
return stat_buf.st_mtime;
}
int net_get_dns_info(dns_info_t *dns_info)
{
FILE *file;
int ret, i, svr_cnt, df;
char name[16], domain[128];
file = fopen(RESOLV_CONF_PATH, "r");
if (!file) {
printf("fopen fail = %s(%d)/n", strerror(errno), errno);
return -errno;
}
i = svr_cnt = df = 0;
while ((ret = fscanf(file, "%s %s", name, domain)) != EOF) {
if (ret < 2) {
printf("fscanf ret=%d/n", ret);
ret = -1;
break;
}
if (svr_cnt < MAX_DNS_SERVERS && !strcmp(name, "nameserver")) {
strcpy(dns_info->dns_svr[svr_cnt++], domain);
printf("dns_svr=%s/n", domain);
}
else if (!strcmp(name, "search")) {
strcpy(dns_info->domain, domain);
printf("domain=%s/n", domain);
df++;
}
}
fclose(file);
printf("svr_cnt=%d, df=%d/n", svr_cnt, df);
if (svr_cnt && df)
ret = 0;
else
ret = -1;
return ret;
}
int main(void)
{
int ret;
dns_info_t dns_info;
time_t mtime;
mtime = net_get_dns_info_mtime();
printf("time = %ld/n",mtime); //time_t st_mtime; 文件内容最后被修改的时间
if ((ret = net_get_dns_info(&dns_info)) < 0)
{
printf("Getting DNS Info error/n");
}
return 0;
}
编译运行:
[plain]
zx@zx:~$ gcc main.c
zx@zx:~$ ./a.out
/etc/resolv.conf: st_mtime=0x5195A7A8
time = 1368762280
dns_svr=127.0.0.1
domain=www.google.com
fscanf ret=1
svr_cnt=1, df=1