您的位置:首页 > 运维架构 > Linux

Linux下c语言通过修改/etc/network/interfaces修改IP

2017-01-03 16:07 204 查看
在ARM平台上做嵌入式开发,发现通过其他系统系统调用去修改IP地址之后,设备会死机。于是采用修改/etc/network/interfaces之后重启的方式修改IP。

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ioctl.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<net/if.h>

//设置IP
void setip(char *buffer)
{
char * FILE_NAME = "/etc/network/interfaces";
FILE * file_fd;
int len = 0;
file_fd = fopen(FILE_NAME,"r+");
if(file_fd == NULL)
{
perror("errno");
}
//跳过开头的116个字节
fseek(file_fd,116,SEEK_CUR);
fwrite(buffer,strlen(buffer),1,file_fd);
fclose(file_fd);
}

//获取IP
void getip(char *buffer)
{
char * FILE_NAME = "/etc/network/interfaces";
FILE * file_fd;
int len = 0;
file_fd = fopen(FILE_NAME,"rb");
if(file_fd == NULL)
{
perror("errno");
}
//跳过开头的116个字节
fseek(file_fd,116,SEEK_CUR);
len = fread(buffer, 1, 13, file_fd);
if(len == -1)
{
printf("File read error!\n");
perror("errno");
}
fclose(file_fd);
}

int main(int argc, char * argv[])
{
char ipbuffer[20]="192.168.1.112";
setip(ipbuffer);
getip(ipbuffer);
printf("ipbuffer is:%s\n",ipbuffer);
system("reboot");
printf("rebooting!!!\n");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: