通过域名查找其IP地址的小程序

C 语言中,标准库调用 gethostbyname() 可以进行名称查找。linux中有一工具nslookup 便是用它实现的。既然如此,所以也试一试能否编出这个工具,但是对gethostbyname陌生,于是查看man gethostbyname,其中介绍了gethostbyname原型,hostent原型,应包含头文件,错误代码以及返回值,很有帮助,比google快速准确。先列出这些概念,再来写程序。

#include <netdb.h>
extern int h_errno;
struct hostent *gethostbyname(const char *name);

struct hostent {
               char  *h_name;            /* official name of host */
               char **h_aliases;         /* alias list */
               int    h_addrtype;        /* host address type */
               int    h_length;          /* length of address */
               char **h_addr_list;       /* list of addresses */
           }

#define h_addr h_addr_list[0] /* for backward compatibility */

The gethostbyname() and gethostbyaddr() functions return the hostent structure or a NULL pointer if an error occurs.

有了这些概念,写程序就如顺水推舟了。代码如下,有几个地方需要注意,第一,要包含几个头文件,最初我忘了加入#include <arpa/inet.h>      /* inet_ntoa() to format IP address */   #include <netinet/in.h>     /* in_addr structure */这两个头文件,编译通过,运行时却产生段错误。参考了一些文章,才发现是缺少头文件的缘故。这种错误极其隐蔽,不明白为什么能够编译通过;第二,要注意声明struct in_addr host_addr变量来存储h_addr,若直接使用h_addr作为inet_ntoa的参数,会报段错误;第三,记得将h_addr转换成*(unsigned long *)类型,否则ip地址不准确。

#include <stdio.h>

#include <stdlib.h>

#include <arpa/inet.h>

#include <netinet/in.h>

#include <netdb.h>



int main(int argc,char **argv){

        if(argc!=2){

                printf("wrong input, you should enter two arguments.\n");

                exit(2);

        }



        struct in_addr host_addr;

        struct hostent * hostbyi;

        hostbyi=gethostbyname(argv[1]);



        if(hostbyi==NULL){

                printf("wrong in gethostbyname()\n");

                exit(2);

        }

#if 1

        host_addr.s_addr=*((unsigned long *)hostbyi->h_addr);

#else

        host_addr.s_addr=*hostbyi->h_addr;

#endif



        fprintf(stdout,"host ip:%s\n",inet_ntoa(host_addr));

        return 0;

}

 

注:代码很粗糙,如有画蛇添足之嫌,请指出,非常感谢!

你可能感兴趣的:(IP地址)