Linux 网络编程基础(2)-- 获取主机信息

时间:2023-03-09 19:33:19
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 = ;
char ip[]={};
char *host = "www.sina.com.cn";
struct hostent *ht = NULL;
ht = gethostbyname(host);
if (ht) {
printf("Name: %s\n",ht->h_name);
printf("Type: %s\n",ht->h_addrtype==AF_INET?"AF_INET":"AF_INET6");
printf("Length of the host: %d\n",ht->h_length); for(i = ;ht->h_aliases[i];i++){
printf("Aliase: %s\n",ht->h_aliases[i]);
}
if(ht->h_addr_list[] ==NULL)
printf("No Ip \n");
for(i = ; 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("\n");
}
}
return ;
}

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

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

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

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

下一篇:数据的IO和复用