Hi,
I'm trying to set the gateway with my c++ program. My function receive the gateway on the first parameter.
The return of execution of ioctl() is 0, so it's working good, but when I run the "route" command on console, the configured gateway isn't there.
Check the output and the function below:
$ route
Quote:
Destination Gateway Genmask Flags Metric Ref Use Iface
10.0.0.0 * 255.0.0.0 U 0 0 0 eth0
|
Code:
int gateWayConfig(string gateWay) {
int result = ERROR; //retorno da função
try {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
gateWay = formatIp(gateWay); //converts 192.168.000.001 to 192.168.0.1
if (sockfd > 0) {
struct sockaddr_in *dst, *gw, *mask;
struct rtentry route;
printf("gateway: %s\n", gateWay.c_str());
printf("gateway: %d\n", inet_addr(gateWay.c_str()));
memset(&route, 0, sizeof (struct rtentry));
dst = (struct sockaddr_in *) (&(route.rt_dst));
gw = (struct sockaddr_in *) (&(route.rt_gateway));
mask = (struct sockaddr_in *) (&(route.rt_genmask));
// Make sure we're talking about IP here
dst->sin_family = AF_INET;
gw->sin_family = AF_INET;
mask->sin_family = AF_INET;
// Set up the data for removing the default route
dst->sin_addr.s_addr = 0;
gw->sin_addr.s_addr = 0;
mask->sin_addr.s_addr = 0;
route.rt_flags = RTF_UP | RTF_GATEWAY;
// Remove the default route
ioctl(sockfd, SIOCDELRT, &route);
// Set up the data for adding the default route
dst->sin_addr.s_addr = 0;
gw->sin_addr.s_addr = inet_addr(gateWay.c_str());
mask->sin_addr.s_addr = 0;
route.rt_metric = 1;
route.rt_flags = RTF_UP | RTF_GATEWAY;
// Remove this route if it already exists
ioctl(sockfd, SIOCDELRT, &route);
// Add the default route
if (ioctl(sockfd, SIOCADDRT, &route) == -1) {
// *** The error never occurs ***
fprintf(stderr, "Adding default route: %d", errno);
}
shutdown(sockfd, SHUT_RDWR);
close(sockfd);
}
printf("result: %d\n", result);
} catch (...) {
}
return result;
}
Could someone help me to solve this issue?
I tried to use system() function to set the gateway using:
system("route del default");
system("route add default gw 10.100.40.1 dev eth0");
But didn't work too. :/
Thanks in advance