分类: LINUX
2012-07-11 14:16:48
最近有个项目,要求在程序中,对嵌入式linux系统设置网卡的IP地址,子网掩码,网关,虽说直接调用系统自带的ifconfig,route等命令可以实现但总觉得不够优雅,于是写了个利用ioctl直接设置的程序,供大家参考。
#include
#include
#include
#include
#include
#include
#include
#include
//#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//ifname是网卡名,比如eth0,ipaddr是IP地址
int ifconfig(const char *ifname, const char *ipaddr,const char *netmask,const char *gwip)
{
struct sockaddr_in sin;
struct ifreq ifr;
int fd;
bzero(&ifr, sizeof(struct ifreq));
if (ifname == NULL)
return (-1);
if (ipaddr == NULL)
return (-1);
if(gwip == NULL)
return(-1);
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
perror( "Not create network socket connection\n ");
return (-1);
}
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(ipaddr);
memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
if (ioctl(fd, SIOCSIFADDR, &ifr) < 0)
{
perror( "Not setup interface\n ");
return (-1);
}
///////////////////////////////////////////
bzero(&ifr, sizeof(struct ifreq));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(netmask);
memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
if(ioctl(fd, SIOCSIFNETMASK, &ifr ) < 0)
{
perror("net mask ioctl error/n");
return (-1);
}
/////////////////////////////////
struct rtentry rm;
bzero(&rm, sizeof(struct rtentry));
rm.rt_dst.sa_family = AF_INET;
rm.rt_gateway.sa_family = AF_INET;
rm.rt_genmask.sa_family = AF_INET;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(gwip);
memcpy(&rm.rt_gateway, &sin, sizeof(sin));
rm.rt_dev = (char *)ifname;
rm.rt_flags = RTF_UP | RTF_GATEWAY ;
if(ioctl(fd, SIOCADDRT, &rm ) < 0)
{
perror("gateway ioctl error/n");
return (-1);
}
/////////////////////////////////
ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0)
{
perror( "SIOCSIFFLAGS ");
return (-1);
}
return (0);
}