问题
I've written simple C++ function, that adds new route:
void addRoute()
{
int fd = socket( PF_INET, SOCK_DGRAM, IPPROTO_IP );
struct rtentry route;
memset( &route, 0, sizeof( route ) );
struct sockaddr_in *addr = (struct sockaddr_in *)&route.rt_gateway;
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = inet_addr( "192.168.20.1" );
addr = (struct sockaddr_in*) &route.rt_dst;
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = inet_addr( "10.0.0.50" );
addr = (struct sockaddr_in*) &route.rt_genmask;
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = INADDR_ANY;
route.rt_flags = RTF_UP | RTF_GATEWAY;
route.rt_metric = 0;
int rc = ioctl( fd, SIOCADDRT, &route );
cout << "rc = " << rc << endl; //rc = -1
close( fd );
}
int main()
{
addRoute();
return 0;
}
The problem is ioctl returns -1 (rc = -1). What is wrong with my code? I launch it from root. I want to execute ip route and see this line:
10.0.0.50 via 192.168.20.1 dev vpn_linux
来源:https://stackoverflow.com/questions/57959731/add-route-programmatically-in-c-using-ioctl