zoukankan      html  css  js  c++  java
  • gethostname(获取主机名)、gethostbyname(由主机名获取IP地址)

      int gethostname(char *name, size_t len);
    获取本地主机名存入name[len],成功返回0,失败返回-1;


      struct hostent * gethostbyname(const char * hostname);  //返回对应于给定主机名的包含主机名字和地址信息的hostent结构的指针

      struct hostent
      {
        char *h_name;  //所查询主机规范名
        char **h_aliases;  //
        int h_addrtype;
        int h_length;
        char **h_addr_list;  //本机Ip地址列表, 指针的指针存放所有的IP
      };

    #include<unistd.h>
    #include<sys/types.h>
    #include<sys/socket.h>
    #include<string.h>
    #include<stdlib.h>
    #include<stdio.h>
    #include<errno.h>
    #include<netinet/in.h>
    #include<arpa/inet.h>
    #include<signal.h>
    #include<netdb.h>
    #define ERR_EXIT(m)
        do
        {
            perror(m);
            exit(EXIT_FAILURE);
        }while(0)
    //获取本机IP。
    int getlocalip(char * ip,char *host)
    {
        struct hostent *hp;
        if((hp=gethostbyname(host))==NULL)
            return -1;
        strcpy(ip,inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]));  //还有一个宏  #define  hp->h_addr  hp->h_addr_list[0]
        return 0;
    }
    int main()
    {
        char host[100]={0};
        if(gethostname(host,sizeof(host))<0)
            ERR_EXIT("gethostname error");//错误返回-1
        printf("hostname=%s
    ",host);
        struct hostent *hp;
        if((hp=gethostbyname(host))==NULL)
            ERR_EXIT("gethostbyname error");
        int i=0;//hp->h_addr_list[i]是一个char* ,实际上是一个(struct in_addr)结构指针
        while(hp->h_addr_list[i]!=NULL)
        {
            printf("%s
    ",inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));//获取本地主机IP地址
            i++;//list第一个指向本地IP   char*  inet_ntoa(struct in_addr in);(转换成点分十进制)
        }
        char ip[16]={0};
        getlocalip(ip,host);//list中第一个指向本地IP,实现一个获取本机默认ip的程序。
        printf("local ip=%s
    ",ip);
        return 0;
    }
  • 相关阅读:
    201521123031 《Java程序设计》第14周学习总结
    201521123031 《Java程序设计》第13周学习总结
    软工个人作业5——软件工程总结
    软工网络15个人作业4——alpha阶段个人总结
    软工网络15个人作业3——案例分析
    软件工程网络15结对编程作业
    软工网络15个人阅读作业2——提问题
    软件工程网络15个人阅读作业1(201521123036 曾艺佳)
    Java课程设计
    Java课程设计-学生基本信息管理 201521123036
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/8413000.html
Copyright © 2011-2022 走看看