zoukankan      html  css  js  c++  java
  • Linux 网络编程基础(2)-- 获取主机信息

      前一篇已经介绍了最基本的网络数据结构。这篇介绍一下获取主机信息的函数 

      举个例子,想要通过代码的方式从百度获取当前的时间,怎么做?我们不知道百度的IP地址啊,这代码怎么写?还好,Linux提供了一些API,使得IP与域名之间的转  换变得非常简单。这就是gethostbyname()、gethostbyaddr()。

      首先介绍一个结构体:struct hostent.

      struct hostent {

        char *h_name;          /*主机的正式名称  比如www.google.com*/

        char **h_aliases;       /*主机的别名*/

        int   h_addrtype;        /*主机地址的地址类型   IPv4/IPv6*/

        int   h_length;

        char  **h_addr_list;    /*IP地址列表,  像百度  一个域名对应多个IP地址*/

      };

    #include <netdb.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    /*
      struct hostent {
        char *h_name;          official name for the host
        char **h_aliases;      nake names for the host
        int h_addrtype;        addrres type of host ipv4 or ipv6
        int h_length;          length of the addrres
        char **h_addr_list;    list of addrres 
      }
    */
    
    int main(int argc, char *argv[])
    {
        int i = 0;    
        char ip[32]={};
        char *host = "www.sina.com.cn";
        struct hostent *ht = NULL;
        ht = gethostbyname(host);
        if (ht) {
            printf("Name: %s
    ",ht->h_name);
            printf("Type: %s
    ",ht->h_addrtype==AF_INET?"AF_INET":"AF_INET6");
            printf("Length of the host: %d
    ",ht->h_length);
    
             for(i = 0;ht->h_aliases[i];i++){
                printf("Aliase: %s
    ",ht->h_aliases[i]);
            } 
            if(ht->h_addr_list[0] ==NULL)
                printf("No Ip 
    ");
            for(i = 0; ht->h_addr_list[i]; i++){
                struct in_addr ip_in = *((struct in_addr *)ht->h_addr_list[i]);
                printf("IP:%s",(char *)inet_ntoa(ip_in));
                printf("
    ");
            }
        }
        return 0 ;
    }

      函数gethostbyname()和函数gethostbyaddr()都是不可重入的。也就是说连续调用多次此函数,最后得到只是最后一次的返回结果,所以要保存多次返回的结  果,就要把每次的结果都单独保存。

      上一篇文章中提到如何判断当前主机的字节序,以下代码可以作为参考:

    #include <stdio.h>
    #include <stdlib.h>
    
    union B_L
    {
          char INT[4];
          char CH[2];
    };
    int main(int argc, char *argv[])
    {
      union B_L bl;
      bl.INT[0] = 0x00;
      bl.INT[1] = 0x00;
      bl.INT[2] = 0xff;
      bl.INT[3] = 0xff;
      printf("%x%x",bl.CH[0],bl.CH[1]);
      system("PAUSE");    
      return 0;
    }

        如果输出结果为:00表示主机的字节序为大端字节序,否则为小端字节序。可以自己试着分析一下为啥。。

         下一篇:数据的IO和复用

  • 相关阅读:
    this,static,执行程序的顺序等等留意点
    PHP 中的 $this, static , self ,parent 等等关键字的总结
    css的继承之width属性(容易忽略)
    SDK和API之间有什么关系呢?
    JDK8下载账号分享
    Google大数据三篇著名论文-中文版
    HBase性能优化方法总结
    Hbase原理解析
    Java多线程
    XMind 是一个全功能的思维导图和头脑风暴软件,为激发灵感和创意而生
  • 原文地址:https://www.cnblogs.com/tju-gsp/p/3653113.html
Copyright © 2011-2022 走看看