Linux下簡單的DNS例子

來源:互聯網
上載者:User

題目:DNS Client
要求:案例類比一個DNS用戶端程式,根據指定的DNS伺服器,對網域名稱實施正向、逆向解析。
問題:目前只能用系統預設DNS伺服器,無法逆向解析外網IP。
使用方法:
編譯:$gcc -o dns dns.c
運行:$./dns www.whu.edu.cn
$./dns 192.168.0.51(我的內網IP)

程式:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main(int argc ,char *argv[])
{
        struct sockaddr_in addr;
        struct hostent *host;
        char **alias;
        
        if(argc!=2)
        {
         fprintf(stderr,"Usage:%s hostname|ip..\n\a",argv[0]);
         exit(1);
        }
        
        /* 這裡我們假設是IP,通過IP獲得主機資訊*/   
        if(inet_aton(argv[1],&(addr.sin_addr))!=0)
        {
           host=gethostbyaddr((char *)&(addr.sin_addr),4,AF_INET); 
           printf("Address information of Ip %s\n",argv[1]); 
        } 
        else 
        {
        /* 否則使用者應該輸入的是網域名稱,通過網域名稱找主機資訊*/
           host=gethostbyname(argv[1]);
           printf("Address information of host %s\n",argv[1]); 
        }
        if(host==NULL)
        {
        /* 都不是,算了不找了*/
           printf("No Information found");
           exit(1);
        }
        /*列印主機正式名稱*/
        printf("Official host name:\n%s\n\n",host->h_name);
        /*列印主機其他名稱*/
        printf("Name aliases:\n");
        for(alias=host->h_aliases;*alias!=NULL;alias++)
        printf("%s\n",*alias);
        /*列印主機系列IP*/
        printf("\nIp address:\n");
        for(alias=host->h_addr_list;*alias!=NULL;alias++)
        printf("%s\n",inet_ntoa(*(struct in_addr *)(*alias)));
}

打包下載:
http://files.cnblogs.com/lzcarl/dns.rar

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.