===== How to add/del route in C ===== #include #include #include #include #include #include #include #include #include #define ROUTE_ADD SIOCADDRT #define ROUTE_DEL SIOCDELRT int route_edit(int action, struct sockaddr_in destination, struct sockaddr_in gateway); int main (int argc, char *argv[]) { struct sockaddr_in dest, gw; /* Fill structures with 0 */ memset (&dest, 0, sizeof(dest)); memset (&gw, 0, sizeof(gw)); dest.sin_family = AF_INET; dest.sin_addr.s_addr = inet_addr("1.2.3.4"); gw.sin_family = AF_INET; gw.sin_addr.s_addr = inet_addr("127.0.0.1"); printf("-> %d\n", route_edit(ROUTE_ADD, dest, gw)); printf("-> %d\n", route_edit(ROUTE_DEL, dest, gw)); exit (0); } /* Add or delete a route */ int route_edit(int action, struct sockaddr_in destination, struct sockaddr_in gateway) { struct rtentry new_route; int skt; /* Fill structure */ memset(&new_route, 0, sizeof(struct rtentry)); /* Copy sockadd_in structure to new_route */ memcpy((char *) &new_route.rt_dst, (char *) &destination, (sizeof destination)); memcpy((char *) &new_route.rt_gateway, (char *) &gateway, (sizeof gateway)); /* Open socket */ if ((skt = socket(AF_INET, SOCK_DGRAM, 0)) < 0) return -1; /* Proceed */ { int ret; ret = ioctl(skt, action, &new_route); /* Close socket */ close (skt); return ret; } } ~~DISCUSSION~~