public RouteConfig getDefaultRoute(String iface) { RouteConfig[] routes = getRoutes(); RouteConfig defaultRoute; ArrayList<RouteConfig> defaultRoutes = new ArrayList<RouteConfig>(); // Search through routes and construct a list of all default routes for the specified interface for (int i = 0; i < routes.length; i++) { if (routes[i].getInterfaceName().compareTo(iface) == 0 && routes[i].getDestination().getHostAddress().compareTo("0.0.0.0") == 0) { defaultRoutes.add(routes[i]); } } // If no default routes exist, return null if (defaultRoutes.size() == 0) { s_logger.debug("No default routes exist for inteface: " + iface); return null; } // Set the default route to the first one in the list defaultRoute = (RouteConfig) defaultRoutes.get(0); // Search for the default route with the lowest metric value for (int i = 1; i < defaultRoutes.size(); i++) { if (defaultRoute.getMetric() > ((RouteConfig) defaultRoutes.get(i)).getMetric()) { defaultRoute = (RouteConfig) defaultRoutes.get(i); } } s_logger.info("Default route found for interface: " + iface); s_logger.debug("Default route:\n" + defaultRoute.getDescription()); return defaultRoute; }
public void addStaticRoute( IPAddress destination, IPAddress gateway, IPAddress netmask, String iface, int metric) throws Exception { RouteConfig tmpRoute = null; StringBuffer command = new StringBuffer(); command.append("route add -net " + destination.getHostAddress() + " "); if (netmask != null) { command.append("netmask " + netmask.getHostAddress() + " "); } if (gateway != null) { if ((gateway.getHostAddress().compareTo("0.0.0.0") != 0) && (gateway.getHostAddress().compareTo("127.0.0.1") != 0)) { command.append("gw " + gateway.getHostAddress() + " "); } } if (iface != null) { command.append("dev " + iface + " "); } if (metric != 0 && metric != -1) { command.append("metric " + metric); } SafeProcess proc = null; try { s_logger.debug("Executing command: " + command.toString()); proc = ProcessUtil.exec(command.toString()); proc.waitFor(); if (proc.exitValue() != 0) { s_logger.error("Error adding static Route: " + command.toString()); throw new Exception("Error adding Static Route"); } } catch (IOException e) { s_logger.error("Error executing command: route -n"); throw e; } finally { if (proc != null) ProcessUtil.destroy(proc); } if (destination instanceof IP4Address) { tmpRoute = new RouteConfigIP4( (IP4Address) destination, (IP4Address) gateway, (IP4Address) netmask, iface, -1); } else if (destination instanceof IP6Address) { tmpRoute = new RouteConfigIP6( (IP6Address) destination, (IP6Address) gateway, (IP6Address) netmask, iface, -1); } s_logger.info("Static route added successfully"); s_logger.debug(tmpRoute.getDescription()); }