#include <stdio.h>
#include <string.h>
FILE *fp = NULL;
#define NETWORK_FILE "/etc/network/interfaces"
static char* getNetworkInfo(char *maches)
{
char szBuf[64];
char *szNetwork=NULL;
int i = 0;
if((fp=fopen(NETWORK_FILE, "r"))==NULL) //判断文件是否为空
{
printf( "Can 't open file!\n");
return 0;
}
while(fgets(szBuf,128,fp)) //从文件开关开始向下读,把读到的内容放到szBuf中
{
if(strstr(szBuf,maches) != NULL) //找到maches在文件中第一次出现的位置。。如address
{
for(i =0;i < strlen(szBuf);i++)
{
if(isdigit(*(szBuf+i))) //从szBuf字符串中找出数字。
{
szNetwork = (char*)malloc(strlen(szBuf)); //为szNetwork分配内存
strcpy(szNetwork,szBuf+i);
szNetwork[strlen(szNetwork)-1] = '\0';
fclose(fp);
return szNetwork;
}
}
}else
continue;
}
fclose(fp);
return szNetwork;
}
int main()
{
char *IPaddress;
char *netmask;
char *gateway;
IPaddress = getNetworkInfo("address"); //找到 LINUX 配制文件中的 interfaces 文件 匹配IP 。然后读出来
netmask = getNetworkInfo("netmask"); //子网掩码
gateway = getNetworkInfo("gateway"); //默认网关
printf("IPaddress:%s\n",IPaddress);
printf("netmask:%s\n",netmask);
printf("gateway:%s\n",gateway);
}
/*****************************
* interfaces 里的内容 *
* *
*****************************/
/*****************************
iface lo inet loopback
auto eth0
iface eth0 inet static
address 192.168.1.139
netmask 255.255.255.0
gateway 192.168.1.1
*****************************/
static void writeAddr(char addressbuf[255]) //IP 写入
{
FILE* fp=NULL;
int i,Lid = -1;
char szBuf[128];
char szTemp[128];
char szTmp[20][256];
memset(szTmp,0,sizeof(szTmp));
memset(szBuf,0,sizeof(szBuf));
if((fp=fopen(NETWORK_FILE, "r+"))==NULL)
{
printf( "setIP Can 't open file!\n");
return;
}
while(fgets(szBuf,256,fp))
{
Lid++;
if('#' != *szBuf)
{
if(strstr(szBuf,"gateway") != NULL)
{
memset(szTemp,0,sizeof(szTemp));
snprintf(szTemp, sizeof(szTemp), "\tgateway %s\n",addressbuf);
strcpy(szTmp[Lid],szTemp);
}else
strcpy(szTmp[Lid],szBuf);
}else{
strcpy(szTmp[Lid],szBuf);
}
}
fclose(fp);
printf("%s\n",szTmp[6]);
if((fp=fopen(NETWORK_FILE, "w"))==NULL)
{
printf( "writeIP Can 't open file!\n");
return;
}else{
for(i = 0;i <=Lid;i++)
fputs(szTmp[i],fp);
fclose(fp);
}
return;
}