今天在网上找了一下希望能找到用系统函数更新gateway的函数没有找到。看了一下busybox中关于route命令的实现,发现也比较麻烦。
最后只好用老办法了,用system来调用route的命令了。下面是代码。
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *pfile=NULL;
ssize_t read;
size_t len=0;
char* line=NULL;
char *c=NULL;
len=256;
char routeinfofile[]="route2.txt";
char shellcmd[128];
char ipaddr[20];
memset(shellcmd,0,sizeof(shellcmd));
sprintf(shellcmd,"route >%s",routeinfofile);
system(shellcmd);
line=(char*)malloc(len);
if(line==NULL) return;
if(NULL==(pfile=fopen(routeinfofile,"r")) )
{
printf("/ncannot open route.txt/n");
return;
}
while((read=getline(&line,&len,pfile))!=-1)
{
printf("Retriveved line of length %zu :/n",read);
printf("%s",line);
c=strstr(line,"default");
if(c)
{
printf("/nfound default:line=(%p) c=(%p)",line,c);
int i;
int posbegin=0;
int posend=0;
for(i=7;i<read;i++)
{
if((line[i]!=' ')&&(posbegin==0))
{
posbegin=i;
}
if(posbegin>0)
{
if((line[i]==' ')&&(posend==0))
{
posend=i;
break;
}
}
}
if(posend>0)
{
printf("/nthe IP address founded is begin(%d) end(%d):",posbegin,posend);
memset(ipaddr,0,sizeof(ipaddr));
for(i=posbegin;i<posend;i++)
{
printf("%c",line[i]);
if((i-posbegin)<sizeof(ipaddr))
ipaddr[i-posbegin]=line[i];
}
printf("/n");
memset(shellcmd,0,sizeof(shellcmd));
sprintf(shellcmd,"route del default gw %s dev eth0",ipaddr);
system(shellcmd);
}
}
else printf("/nnot found default. line=(%p) c=(%p)",line,c);
}
if(line) free(line);
memset(shellcmd,0,sizeof(shellcmd));
sprintf(shellcmd,"route add default gw %s dev eth0","192.168.1.1");
system(shellcmd);
return;
}