Add route programmatically in C++ using ioctl

纵然是瞬间 提交于 2020-01-02 07:29:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!