Linux中获取本机网络信息的几个函数及应用
一、读取/etc/hosts 几个函数
头文件<netdb.h>
1.void sethostent(int stayopen);//开打/etc/hosts 配置文件
2.struct hostent * gethostent(void);//读取配置文件
3.void enthostent(void);//关闭 /etc/hosts 文件
二、读取/etc/protocols文件的几个函数
1.struct protoent *getprotobyname(cosnt char *name);
struct protent
{
char *p_name;
char **p_aliases;
int p_proto;
}
#include <stdio.h> #include <netdb.h> #include <sys/utsname.h> main() { printf("============获取host信息====================\n"); struct hostent *ent; /*打开主机配置数据文件*/ sethostent(1); while(1) { ent=gethostent(); if(ent==0)break; printf("主机名:%s\t",ent->h_name); printf("IP地址:%hhu.%hhu.%hhu.%hhu\t",ent->h_addr[0],ent->h_addr[1],ent->h_addr[2],ent->h_addr[3]); printf("别名:%s\n",ent->h_aliases[0]); } endhostent(); //获取本机信息 printf("==============获取本机信息==================\n"); struct protoent *ent2; struct utsname name; ent2=getprotobyname("tcp"); printf("proto:%d\n",ent2->p_proto); uname(&name); printf("machine:%s\n",name.machine); printf("nodename:%s\n",name.nodename); printf("sysname:%s\n",name.sysname); //通过域名获取IP printf("========通过域名获取IP=====================\n"); struct hostent *ent3; ent3=gethostbyname("www.baidu.com"); printf("%hhu.%hhu.%hhu.%hhu\n",ent3->h_addr_list[0][0],ent3->h_addr_list[0][1],ent3->h_addr_list[0][2],ent3->h_addr_list[0][3]); }
============获取host信息====================
主机名:localhost IP地址:127.0.0.1 别名:localhost.localdomain
主机名:localhost IP地址:127.0.0.1 别名:localhost.localdomain
==============获取本机信息==================
proto:6
machine:x86_64
nodename:localhost.localdomain
sysname:Linux
========通过域名获取IP=====================
115.239.210.26
[root@localhost day09]#