使用ioctl添加网关产生Network is unreachable的原因

代码如下

#define DBG_ERR(x...)        perror(x)
int net_add_gateway(in_addr_t addr)
{
	struct rtentry rt;
	int skfd;
	struct sockaddr_in sa = {
		sin_family:PF_INET,
		sin_port:0
	};

	/* Clean out the RTREQ structure. */
	memset((char *) &rt, 0, sizeof(struct rtentry));

	/* Fill in the other fields. */
	rt.rt_flags = (RTF_UP | RTF_GATEWAY);

	rt.rt_dst.sa_family = PF_INET;
	rt.rt_genmask.sa_family = PF_INET;

	sa.sin_addr.s_addr = addr;
	memcpy((char *) &rt.rt_gateway, (char *) &sa, sizeof(struct sockaddr));

	/* Create a socket to the INET kernel. */
	if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		DBG_ERR("socket error");
		return -1;
	}
	/* Tell the kernel to accept this route. */
	if (ioctl(skfd, SIOCADDRT, &rt) < 0) {
		DBG_ERR("net_add_gateway: ioctl SIOCADDRT");
		close(skfd);
		return -1;
	}
	/* Close the socket. */
	close(skfd);
	return (0);
}

在添加网关时,只要网关IP与IP地址不在同一个网段内,ioctl便会引起Network is unreachable错误.只要将ip、netmask、gateway设置对了即可.

你可能感兴趣的:(struct,socket,UP,NetWork,rtf)