LinuxÒÁµéÔ°ÂÛ̳'s Archiver

billy_chxf ·¢±íÓÚ 2003-10-15 09:03

¸ßÊÖ°ïæ·ÖÎöÏÂÃæÒ»¶ÎC£¨unix£©µÄ´úÂ룬ÓйØDNS½âÎöµÄ£¬µ÷ÓÃÁËres_init()£¬res_query£¨£©µÈº¯Êý¡£

#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ÏÂÔËÐÐÕý³££¬µ«ÊÇÄõ½¿Í»§ÄDZߵÄsolarisÏÂÖØÐ±àÒëÖ´ÐУ¨ÔÚûÓÐÅäÖÃÎļþ/etc/resolv.confµÄÇé¿öÏ£©È´ÎÞ·¨½âÎö£¬µ«Êǵ±ÅäÖÃÁË/etc/resolv.conf£¨DNS£©ºó£¬ÔËÐÐʱ¼´Ê¹ÄãÖ¸¶¨DNSΪ1.1.1.1Ò²Äܳɹ¦½âÎö¡£

Ò³: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.