Linux C 獲取本機相關信息
/@Abstract getHostInformation */include <stdio.h>
include <stdlib.h>
include <netdb.h>
include <arpa/inet.h>
define NET_ADDR_STR_LEN 16 //16個字節,用于存放點分十進制IP地址的字符串長度
int main(int argc,char *argv) { struct hostent host; //存放主機信息 char addr_p[NET_ADDR_STR_LEN]; //用于存放點分十進制IP地址的字符串 int i; if((host = gethostent()) == NULL) { perror("fail to get host's information\n"); exit(1); } printf("hostName: %s\n" , host->h_name); for(i = 0 ; host->h_aliases[i] != NULL;i++) { printf("%s\n" , host->h_aliases[i]); //主機別名列表,可以又很多,以二維數組形式存儲 h_aliases[0] 為主機IP } if(host->h_addrtype == AF_INET) //判斷IP類型是否是ipv4 { printf("at_inet\n"); } else { printf("unix_inet\n"); } printf("len%d\n",host->h_length); //地址長度 for(i = 0 ; host->h_addr_list[i] != NULL ; i++) { //該地址以二進制形式存儲,轉換為字符串的形式 printf("%s\n",inet_ntop(host->h_addrtype,host->h_addr_list[i],addr_p,NET_ADDR_STR_LEN)); //打印主機IP地址 } return 0; }</pre>