zoukankan      html  css  js  c++  java
  • socket学习笔记——获取域名与IP(linux)

    gethostbyname.c

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <unistd.h>
     4 #include <arpa/inet.h>
     5 #include <arpa/inet.h>
     6 #include <netdb.h>
     7 
     8 int main(int argc,char* argv[])
     9 {
    10     int i;
    11     struct hostent* host;
    12     if(argc != 2)
    13     {
    14         printf("usage: %s <addr>
    ",argv[0]);
    15         exit(1);
    16     }
    17 
    18     host = gethostbyname(argv[1]);
    19     if(!host)
    20     {
    21         printf("get host error......
    ");
    22         exit(1);
    23     }
    24     printf("official name:%s
    ",host->h_name);
    25     for(i = 0;host->h_aliases[i];i++)
    26         printf("access %d; %s
    ",i+1,host->h_aliases[i]);
    27     printf("address type:%s 
    ",(host->h_addrtype==AF_INET)?"AF_INET":"AFINET6");
    28     for(i = 0;host->h_addr_list[i];i++)
    29         printf("IP addr %d: %s 
    ",i+1,inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
    30     return 0;
    31 }

    gethostbyaddr.c

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 #include <unistd.h>
     5 #include <arpa/inet.h>
     6 #include <netdb.h>
     7 
     8 int main(int argc,char* argv[])
     9 {
    10     int i;
    11     struct hostent* host;
    12     struct sockaddr_in addr;
    13     if(argc != 2)
    14     {
    15         printf("usage :%s <ip>
    ",argv[0]);
    16         exit(1);
    17     }
    18 
    19     memset(&addr,0,sizeof(addr));
    20     addr.sin_addr.s_addr = inet_addr(argv[1]);
    21     host = gethostbyaddr((char*)&addr.sin_addr,4,AF_INET);
    22     if(!host)
    23     {
    24         printf("get host error
    ");
    25         exit(1);
    26     }
    27 
    28     printf("official name;%s 
    ",host->h_name);
    29     for(i = 0;host->h_aliases[i];i++)
    30         printf("aliases %d:%s
    ",i,host->h_aliases[i]);
    31     printf("address type:%s
    ",(host->h_addrtype==AF_INET)?"AF_INET":"AF_INET6");
    32     for(i = 0;host->h_addr_list[i];i++)
    33         printf("IP addr %d;%s
    ",i+1,inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
    34     return 0;
    35 }
  • 相关阅读:
    HDU 1031 Design TShirt
    普利姆(Prime)算法
    hdu 2601 An easy problem
    克鲁斯卡尔(Kruskal)算法
    双调欧几里德旅行商问题hdu 2224 The shortest path POJ 2677Tour
    求一个数个各位相加的结果时
    C语言中各种类型的范围
    获取浏览器的scrollTop有几点小疑问
    学习,学习javascript
    各种翻页的效果! FILTER: revealTrans使用说明
  • 原文地址:https://www.cnblogs.com/boyiliushui/p/4736133.html
Copyright © 2011-2022 走看看