gethostname、gethostbyname

gethostname():返回本地主机的标准主机名

 

原型:

#include<unistd.h>

int gethostname(char *name, size_t len);

 

参数说明:

name:  接收缓冲区,字节长度必须为len,或更长,存获取主机名

len:      接收缓冲区name的最大长度

 

返回值:

       如果函数成功,返回0,如果发生错误,返回-1,错误号存放在外部变量errno中。

 

/*
gethostname.c
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

#define ERR_EXIT(m) \
    do {\
        perror(m); \
        exit(EXIT_FAILURE); \
    }while(0);

int main()
{
    char name[256];
    if (gethostname(name, sizeof(name)))
    {
        ERR_EXIT("gethostname");
    }

    printf("hostname = %s\n",name);
    
    return 0;        
}

 

运行结果:

 

 

gethostbyname()

 

函数原型:

#include <netdb.h>
#include <sys/socket.h>
struct hostent *gethostbyname(const char *name);

 

参数说明:

name:域名或主机名

 

返回值:

调用成功,返回一个hostent结构,若函数调用失败,返回NULL

 

返回的hostent结构体类型的指针:

struct hostent {

    char *h_name;   /* official name of host */
    char **h_aliases;  /*alias list */
    int h_addrtype;  /* host address type */
    int h_length; /* length of address */
    char **h_addr_list;   /* list of addresses*/

}

#define h_addr h_addr_list[0] /* for backward compatibility */

 

hostent->h_name 

   表示的是主机的规范名。例如www.google.com的规范名其实是www.l.google.com.

 

 hostent->h_aliases 

    表示的是主机的别名www.google.com就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。

 

  hostent->h_addrtype 

    表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是ipv6(AF_INET6)

 

  hostent->h_length 

    表示的是主机ip地址的长度

 

  hostent->h_addr_list 

  表示的是主机的ip地址,注意,这个是网络字节存储的。千万不要直接用printf带%s参数来打这个东西,会有问题的哇。所以到真正需要打印出这个IP的话,需要调用inet_ntop()。

 

  const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt); 

这个函数,是将类型为af的网络地址结构src,转换为主机序的字符串形式,存放在长度为cnt的字符串中。返回指向dst的一个指针。如果函数调用错误,返回值是NULL。

 

/*
gethostbyname.c
*/
#include<stdio.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/socket.h>

int main()
{
    char name[256];
    gethostname(name,sizeof(name));
    printf("hostname = %s\n",name);

    struct hostent *hp;
    if ((hp = gethostbyname(name)) == NULL)
    {
        printf("gethostbyname error");
    }

    int i = 0;
    while(hp->h_addr_list[i] != NULL)
    {
        printf("hostname : %s\n",hp->h_name);
        printf("\tip:%s\n",inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));
        i++;
    }
    return 0;
}

 

运行结果:

 

 

 

 

 

 

posted @ 2019-11-07 11:25  王清河  阅读(400)  评论(0编辑  收藏  举报