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;
}
原文地址:https://www.cnblogs.com/wsw-seu/p/8413000.html