最近看了一下net-tools的源码,然后简易实现了ifconfig命令。
目前可以支持修改IP,MAC地址,netmask 以及gateway。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/route.h>
#include <linux/if_vlan.h>
#include <linux/sockios.h>
#include <fcntl.h>
#include <errno.h>
static int is_valid_ip(const char *ip)
{
if (ip == NULL || strlen(ip) < 7)
{
return -1;
}
int len = strlen(ip);
const char *start = ip;
const char *end = ip + len - 1;
int ret = 0;
int dot_count = 0;
int cur_val = 0;
int val = -1;
while (end > start && isspace(*end))
{
--end;
}
while (start < end && isspace(*start))
{
++start;
}
if (start >= end || isdigit(*start) == 0|| isdigit(*end) == 0)
{
return -1;
}
while (start <= end)
{
while (start <= end && '0' <= *start && *start <= '9')
{
cur_val = 10 * cur_val + (*start - '0');
if (cur_val <