通过SIOCADDRT添加默认网关时指定接口

我正在尝试通过SIOCADDRT和ioctl()设置机器的默认网关.我在网上找到了下面的片段,效果很好:

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( "10.0.2.2" );

addr = (struct sockaddr_in*) &route.rt_dst;
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = INADDR_ANY;

addr = (struct sockaddr_in*) &route.rt_genmask;
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = INADDR_ANY;

// TODO Add the interface name to the request
route.rt_flags = RTF_UP | RTF_GATEWAY;
route.rt_metric = 0;

int rc = ioctl( fd, SIOCADDRT, &route );
// [...]

现在在此代码段中使用TODO …您实际上如何指定要使用的接口?当我执行此代码时,它似乎在我的机器上是默认的eth0(这是我唯一的接口). route.h标头中rt_entry结构的定义如下(也可用here):

   /* This structure gets passed by the SIOCADDRT and SIOCDELRT calls. */
   struct rtentry {
    unsigned long   rt_pad1;
    struct sockaddr rt_dst;     /* target address       */
    struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY)   */
    struct sockaddr rt_genmask; /* target network mask (IP) */
    unsigned short  rt_flags;
    short       rt_pad2;
    unsigned long   rt_pad3;
    void        *rt_pad4;
    short       rt_metric;  /* +1 for binary compatibility! */
    char *rt_dev;   /* forcing the device at add    */
    unsigned long   rt_mtu;     /* per route MTU/Window     */
    #define rt_mss  rt_mtu          /* Compatibility :-(            */
    unsigned long   rt_window;  /* Window clamping      */
    unsigned short  rt_irtt;    /* Initial RTT          */
};

谢谢.

解决方法:

显然,您可以使用两个字段来指定接口:

struct ifnet *rt_ifp;

struct ifaddr *rt_ifa;

These two fields represent the “answer”, as it were, to the question posed by a route
lookup; that is, they name the interface and interface address to be
used in sending a packet to the destination or set of destinations
which this route represents.

更新:
sturct中有一个rt_dev字段,我认为您可以将其设置为接口名称:

char ifname[] = "eth1";
rtentry.rt_dev = ifname;
上一篇:路由路径中的Symfony2特殊字符


下一篇:Linux静态路由:Ping专用网络(连接网络图)