linux下获得系统信息(ip地址)

  在linux下获取系统的IP地址的方法有很多种,今天记录的是通过获取系统信息来获取系统的IP地址。

  由于在linux下通过系统API获取系统信息的方法相似,我们可以依照获取IP地址的方法获取其他信息。

  用到的系统API有:

1 #include <unistd.h>
2 
3 int gethostname(char *name, size_t len);
4 成功返回0,错误返回-15 
6 #include <netdb.h>
7 
8 struct hostent *gethostbyname(const char *name);
9 成功返回struct hostent指针,错误返回NULL

  struct的结构如下:  

1 struct hostent {
2     char  *h_name;            /* official name of host */
3     char **h_aliases;         /* alias list */
4     int    h_addrtype;        /* host address type */
5     int    h_length;          /* length of address */
6     char **h_addr_list;       /* list of addresses */
7 }

  其中gethostname用来获取主机名,并且存储在name所指的缓冲区中,参数len标识name所指的缓冲区的大小。

  在获得主机名后调用gethostbyname获得主机信息的结构(struct hostent),然后提取出我们需要的信息(ip)即可。

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <netdb.h>
 4 #include <sys/socket.h>
 5 #include <netinet/in.h>
 6 #include <arpa/inet.h>
 7 
 8 int main() {
 9     char hname[100];
10     struct hostent *hent;
11     int i;
12  
13     //获取主机名
14     gethostname(hname, sizeof(hname));
15 
16     //根据主机名获取主机信息
17     hent = gethostbyname(hname);
18 
19     //列出主机信息
20     printf("hostname: %s
address list: ", hent->h_name);
21 
22     for(i = 0; hent->h_addr_list[i]; i++) {
23         //inet_ntoa()函数是将网络字节的ip地址转换程IP字符串(往往网络字节的都是大端存储,主机字节序列是小端存储)
24         printf("%s	", inet_ntoa(*(struct in_addr*)(hent->h_addr_list[i])));
25     }
26     return 0;
27 }

  

原文地址:https://www.cnblogs.com/wmllz/p/5044160.html