大前端

前端学习之家-大前端

64位Ubuntu系统下测试网络IP出错

#include  <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>  //64bit ubuntu system ,need this head file
  int  main( int  argc,  char   ** argv)
  {
       char     * ptr,  ** pptr;
       struct  hostent  * hptr;
       char    str[32];
      ptr  =  argv[1];
 
       if ((hptr  =  gethostbyname(ptr))  ==  NULL)
      {
          printf( "  gethostbyname error for host:%s\n " , ptr);
           return   0 ;
      }
 
      printf( " official hostname:%s\n " ,hptr -> h_name);
       for (pptr  =  hptr -> h_aliases;  * pptr  !=  NULL; pptr ++ )
          printf( "  alias:%s\n " , * pptr);
 
			printf( "  hptr->h_length:%d\n " , hptr->h_length);
			printf( "  AF_INET:%d\n " , AF_INET);
			printf( "  AF_INET6:%d\n " , AF_INET6);
			printf( "  hptr->h_addrtype:%d\n " , hptr->h_addrtype);
    	printf("no addr list:\n");
    	
       switch (hptr->h_addrtype)
      {
           case  AF_INET:
           case  AF_INET6:
              pptr = hptr->h_addr_list;
              for (;  *pptr != NULL; pptr++ )
                 printf( "  address:%s\n " , inet_ntop(hptr->h_addrtype,*pptr, str,sizeof(str)));
  
                printf( "  first address: %s\n " , inet_ntop(hptr->h_addrtype, hptr->h_addr, str,  sizeof(str)));

           break ;
           default :
              printf( " unknown address type\n " );
           break ;
      }
 
       return   0 ;
  }

输入web地址查询IP,

[desheng@ubuntu:test]$ ./a.out eu-ota.3irobotix.net
 official hostname:eu-ota.3irobotix.net
   hptr->h_length:4
   hptr->AF_INET:2
   hptr->AF_INET6:10
   hptr->h_addrtype:2
 no addr list:
  address:8.209.81.208
   first address: 8.209.81.208

64位Ubuntu系统需要加入这个头文件,#include <arpa/inet.h>,否则一调用inet_ntop()函数就会返回整数,而不是string,如果直接打印就会出现段错误。

发表评论:

Copyright Your WebSite.Some Rights Reserved.