Search code examples
c++croutesnetlink

Adding route with libnl-3-route "Invalid input data or parameter"


I'm trying to adding route (kernel 2.6.32-57) with libnl-3-routing. I use the documentation :

  1. Netlink library
  2. Netlink routing

But the routing chapter is empty... ;)

The problem is the kernel response with "Invalid input data or parameter". I have do some test with use of netlink and i can add a route if i set the following attributes :

  1. interface index
  2. destination address
  3. gateway address
  4. mask

        int ret = 0;
        // Create the route.
        struct rtnl_route* rulesRoute = rtnl_route_alloc();
        rtnl_route_set_iif(rulesRoute, AF_INET); // IPV4
    
        // Set parameters.
        rtnl_route_set_scope(rulesRoute, RT_SCOPE_UNIVERSE);
        rtnl_route_set_table(rulesRoute, RT_TABLE_MAIN);
        rtnl_route_set_protocol(rulesRoute, RTPROT_STATIC);
        uint8_t maskTest = 16;
        rtnl_route_set_scope(rulesRoute, maskTest);
    
        // Set the destination.
        char destinationAddr[] = "0.0.0.0";
        nl_addr* dstAddr = nl_addr_build(AF_INET, destinationAddr, 8);
        ret = rtnl_route_set_dst(rulesRoute, dstAddr);
        if (ret != 0)
            std::cout << "Error in setting destination route: " << nl_geterror(ret) << std::endl;
    
        // Set the next hop.
        struct rtnl_nexthop* route_nexthop = rtnl_route_nh_alloc();
        char gatewayAddr[] = "10.110.0.240";
        nl_addr* gatewAddr = nl_addr_build(AF_INET, gatewayAddr, 12);
        rtnl_route_nh_set_gateway(route_nexthop, gatewAddr);
        rtnl_route_nh_set_ifindex(route_nexthop, 2);
        rtnl_route_add_nexthop(rulesRoute, route_nexthop);
        ret = rtnl_route_add(m_nlSocket, rulesRoute, 0);
        if (ret != 0)
            std::cout << "Kernel response:" << nl_geterror(ret) << std::endl;
    

I add for information my routing table:

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.110.0.0      0.0.0.0         255.255.255.0   U     1      0        0 eth3
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth3
0.0.0.0         10.110.0.1      0.0.0.0         UG    0      0        0 eth3

Thank for helping to solve this issue


Solution

  • The problem come from the bad use of function nl_addr_build.

    Replace by nl_addr_parse() and that's working.

    nl_addr_build : Parse a binary addr

    nl_addr_parse : Parse a char* addr like "10.10.1.10"