我正在尝试通过SIOCADDRT
and设置我机器的默认网关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 */
};
谢谢任何帮助。