3

我正在尝试通过SIOCADDRTand设置我机器的默认网关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在我的机器上(这是我唯一的界面)。rt_entry标头中结构的定义route.h如下(也可在此处获得):

   /* 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          */
};

谢谢任何帮助。

4

1 回答 1

4

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

结构 ifnet *rt_ifp;

结构 ifaddr *rt_ifa;

这两个字段代表了路由查找提出的问题的“答案”;也就是说,它们命名用于将数据包发送到该路由所代表的目的地或目的地集的接口和接口地址。

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

char ifname[] = "eth1";
rtentry.rt_dev = ifname;
于 2013-07-15T07:26:39.933 回答