我尝试通过SIOCADDRT
和ioctl()
设置我的计算机的默认网关。我在网上找到了以下代码片段:#/ p>
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
结构的定义如下(也可用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 */
};
这是任何帮助。
答案 0 :(得分:4)
显然,您可以使用两个字段来指定界面:
struct ifnet * rt_ifp;
struct ifaddr * rt_ifa;
这两个字段代表路线提出的问题的“答案” 抬头;也就是说,它们将接口和接口地址命名为 用于将数据包发送到目的地或目的地集 这条路线代表的是什么。
更新:
在sturct中有一个rt_dev
字段,我想你可以将它设置为接口名称:
char ifname[] = "eth1";
rtentry.rt_dev = ifname;