+ -
当前位置:首页 → 问答吧 → 高手帮忙分析下面一段C(unix)的代码,有关DNS解析的,调用了res_init(),res_query()等函数。

高手帮忙分析下面一段C(unix)的代码,有关DNS解析的,调用了res_init(),res_query()等函数。

时间:2003-10-15

来源:互联网

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <resolv.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <iostream.h>
#include <string>

using namespace std;

extern struct __res_state _res;

#include <iostream>
#include <string>
using namespace std;

string NameServer;
string DomainName;

int ResolvDns(){
        if( inet_addr(NameServer.c_str()) < 0 )
        {
                cout << "Ip " << NameServer.c_str() << " is invalid" << endl;
                return -1;
        }

        int ret;
        ret = res_init();
        if(ret != 0 )
        {
                perror("init error\n");
                return -1;
        }
        _res.retry = 1;
        _res.nscount = 1;
        _res.nsaddr_list[0].sin_addr.s_addr = inet_addr(NameServer.c_str());

        int aslen = 1024;
        u_char aswr[1024];
        memset(aswr, 0, 1024);
        ret = res_query(DomainName.c_str(), ns_c_in, ns_t_a, aswr, 1024);
        if(ret < 0)
        {
                perror("query error\n");
                return -1;
        }
        if(ret > 1024)
        {
                perror("answer 2 long error\n");
                return -1;
        }

        ns_msg ns;
        ns_rr rr;

        int iipcount = 0;

        ret = ns_initparse(aswr, ret, &ns);
        iipcount = ns_msg_count(ns, ns_s_an);
        in_addr in;
        for(int mm=0; mm<iipcount; mm++)
        {
                if(ns_parserr(&ns, ns_s_an, mm, &rr) < 0)
                {
                        perror("parse error\n");
                        continue;
                }
                if(ns_rr_type(rr) == ns_t_a)
                {
                        in.s_addr = htonl(ns_get32(ns_rr_rdata(rr)));
                        cout << "ip: " << inet_ntoa(in) <<endl;
                }
        }
        return 0;
}

int main(int argc, char **argv)
{
        struct hostent* server;

        if(argc != 3)
        {
                cout << "Usage : " << endl;
                cout << "        " << argv[0] << " IP DN" << endl;
                cout << "IP    : ip address of nameserver" << endl;
                cout << "DN    : domain name want to be resolved" << endl;
                return -1;
        }

        NameServer = argv[1];
        DomainName = argv[2];
        ResolvDns();
        return 1;
}
以上这段代码我在公司的solaris下运行正常,但是拿到客户那边的solaris下重新编译执行(在没有配置文件/etc/resolv.conf的情况下)却无法解析,但是当配置了/etc/resolv.conf(DNS)后,运行时即使你指定DNS为1.1.1.1也能成功解析。      

作者: billy_chxf   发布时间: 2003-10-15

热门下载

更多