#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/route.h>
#include <error.h>
#include <unistd.h>
#include <fcntl.h>
int addRoute(char *ipAddr, char *mask,char *gateWay,char* devName)
{
int fd;
int rc = 0;
struct sockaddr_in _sin;
struct sockaddr_in *sin = &_sin;
struct rtentry rt;
do
{
fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
{
printf("addRoute: socket error\n");
rc = -1;
break;
}
//网关
memset(&rt, 0, sizeof(struct rtentry));
memset(sin, 0, sizeof(struct sockaddr_in));
sin->sin_family = AF_INET;
sin->sin_port = 0;
if(inet_aton(gateWay, &sin->sin_addr)<0)
{
printf( "addRoute: gateWay inet_aton error\n" );
rc = -2;
break;
}
memcpy ( &rt.rt_gateway, sin, sizeof(struct sockaddr_in));
((struct sockaddr_in *)&rt.rt_dst)->sin_family=AF_INET;
if(inet_aton(ipAddr, &((struct sockaddr_in *)&rt.rt_dst)->sin_addr)<0)
{
printf( "addRoute: dst inet_aton error\n" );
rc = -3;
break;
}
((struct sockaddr_in *)&rt.rt_genmask)->sin_family=AF_INET;
if(inet_aton(mask, &((struct sockaddr_in *)&rt.rt_genmask)->sin_addr)<0)
{
printf( "addRoute: mask inet_aton error\n" );
rc = -4;
break;
}
if(devName)
rt.rt_dev = devName;
rt.rt_flags = RTF_GATEWAY;
if (ioctl(fd, SIOCADDRT, &rt)<0)
{
printf( "ioctl(SIOCADDRT) error in set_route\n");
rc = -5;
}
}while(0);
close(fd);
return rc;
}
void main()
{
addRoute("192.168.222.0", "255.255.255.0", "192.168.111.1", "ens6");
}
ioctl设置路由
最新推荐文章于 2021-05-04 06:11:55 发布