zoukankan      html  css  js  c++  java
  • 如何打印hostent结构体中的所有数据

    问题:

    hostent是gethostbyname()和gethostbyaddr()都会涉及到的一个结构体。代码如下:

    struct hostent {
      char  *h_name;
      char  **h_aliases;
      int   h_addrtype;
      int   h_length;
      char  **h_addr_list;
      };

    gethostbyname()的原型是:

    struct hostent *gethostbyname(const char *name);
    函数的传入值是域名或者主机名,例如"www.google.com"、"191.168.1.253"等;
    函数的返回值:

    成功时,返回一个指向hostent结构的指针;

    失败时,返回NULL。

    编程调试过程中需要查看所取到的IP地址等信息,所以将hostent的全部内容打印出来就对调试很有帮助了。


    解决办法:

    #include <stdio.h>
    #include <stdlib.h>
    #include <netdb.h>
    #include <sys/socket.h>
    
    int main(int argc, char *argv[])
    {
    	char *ptr,**pptr;
    	struct hostent *host;
    	char str[32];
    	char *hostname;
    
    	if (argc < 2) {
    		fprintf(stderr, "USAGE: ./pri-hostent Hostname(of ip addr such as 192.168.1.101)\n");
    		exit(1);
    	}
    
    	/* get the host name */
    	hostname = argv[1];
    
    	// if ((host = (struct hostent*)gethostbyname(argv[1])) == NULL) {
    	if ((host = (struct hostent*)gethostbyname(hostname)) == NULL) {
    		perror("gethostbyname");
    		return(1);
    	}
    	printf("Host name is: %s\n", host->h_name);
    	/* printf all the aliases of host */
    	for(pptr = host->h_aliases; *pptr != NULL; pptr++) {
    		printf("  alias of host: %s\n",*pptr);
    	}
    	printf("Host addrtype is: %d\n", host->h_addrtype);
    	printf("Host length is: %d\n", host->h_length);
    	// // printf("Host is: %x\n", *((struct in_addr*)host->h_addr));
    	/* printf ip address according to addrtype */
    	switch(host->h_addrtype) {
    		case AF_INET:
    		case AF_INET6:
    			pptr = host->h_addr_list;
    			/* print all the aliases,inet_ntop() is called */
    			for(; *pptr!=NULL; pptr++) {
    				inet_ntop(host->h_addrtype, *pptr, str, sizeof(str));
    				printf("  address: %s\n", str);
    			}
    		break;
    		default:
    			printf("unknown address type\n");
    		break;
    	}
    
    	return 0;
    }
    
    

    程序的运行结果:

    dingq@wd-u1110:~/hwsvn/2sw/1prj_linux/pdu/src/branches/pdu-isocket/isocket$ ./pri-hostent 
    USAGE: ./pri-hostent Hostname(of ip addr such as 192.168.1.101)
    dingq@wd-u1110:~/hwsvn/2sw/1prj_linux/pdu/src/branches/pdu-isocket/isocket$ ./pri-hostent www.google.com
    Host name is: www.l.google.com
      alias of host: www.google.com
    Host addrtype is: 2
    Host length is: 4
      address: 74.125.128.106
      address: 74.125.128.147
      address: 74.125.128.99
      address: 74.125.128.103
      address: 74.125.128.104
      address: 74.125.128.105


  • 相关阅读:
    面试题 31: 求子数组的最大和
    [面试] 结构体占用空间的问题,内存对齐~! 真的懂了,cpu取加快速度,省空间来考虑。
    [计算机] 32768~32767 计算机中的 1 表示
    C#跨线程调用窗体控件
    合并字节数组
    将汉字转化为2位大写的16进制Unicode
    关公与子龙两大杀手
    早年的J2EE笔记
    给小组新成员的一份信
    c++虚函数详解
  • 原文地址:https://www.cnblogs.com/java20130726/p/3218537.html
Copyright © 2011-2022 走看看