java实现rip模拟
时间: 2023-08-16 10:08:35 浏览: 70
RIP (Routing Information Protocol) 是一种基于距离向量算法的动态路由协议,用于在局域网(LAN)或广域网(WAN)上交换路由信息。下面是一个简单的 Java 实现 RIP 协议的模拟代码:
```java
import java.util.*;
public class RIPSimulator {
private static final int MAX_COST = 16;
private static final int INFINITY = 9999;
private static class Route {
int dest;
int cost;
int nextHop;
public Route(int dest, int cost, int nextHop) {
this.dest = dest;
this.cost = cost;
this.nextHop = nextHop;
}
}
private static class Router {
int id;
List<Route> routingTable;
Map<Integer, Integer> neighbors;
public Router(int id) {
this.id = id;
routingTable = new ArrayList<>();
neighbors = new HashMap<>();
}
public void addNeighbor(int neighborId, int cost) {
neighbors.put(neighborId, cost);
routingTable.add(new Route(neighborId, cost, neighborId));
}
public void updateRoutingTable(List<Route> routes) {
boolean changed = false;
for (Route route : routes) {
if (route.cost >= INFINITY) {
continue;
}
int newCost = route.cost + neighbors.get(route.nextHop);
Optional<Route> existingRoute = routingTable.stream()
.filter(r -> r.dest == route.dest)
.findFirst();
if (existingRoute.isPresent()) {
if (newCost < existingRoute.get().cost) {
existingRoute.get().cost = newCost;
existingRoute.get().nextHop = route.nextHop;
changed = true;
}
} else {
routingTable.add(new Route(route.dest, newCost, route.nextHop));
changed = true;
}
}
if (changed) {
System.out.println("Router " + id + " updated routing table:");
printRoutingTable();
}
}
public void printRoutingTable() {
System.out.println("Destination\tCost\tNext Hop");
routingTable.forEach(route -> {
System.out.println(route.dest + "\t\t" + route.cost + "\t\t" + route.nextHop);
});
}
}
public static void main(String[] args) {
List<Router> routers = new ArrayList<>();
// Add routers and their neighbors
Router r1 = new Router(1);
r1.addNeighbor(2, 1);
r1.addNeighbor(3, 3);
r1.addNeighbor(4, 7);
routers.add(r1);
Router r2 = new Router(2);
r2.addNeighbor(1, 1);
r2.addNeighbor(3, 1);
r2.addNeighbor(4, 2);
routers.add(r2);
Router r3 = new Router(3);
r3.addNeighbor(1, 3);
r3.addNeighbor(2, 1);
r3.addNeighbor(4, 2);
routers.add(r3);
Router r4 = new Router(4);
r4.addNeighbor(1, 7);
r4.addNeighbor(2, 2);
r4.addNeighbor(3, 2);
routers.add(r4);
// Simulate RIP updates
for (int i = 0; i < 10; i++) {
for (Router router : routers) {
List<Route> routes = new ArrayList<>();
for (Router neighbor : routers) {
if (router.neighbors.containsKey(neighbor.id)) {
routes.addAll(neighbor.routingTable);
}
}
router.updateRoutingTable(routes);
}
}
}
}
```
此代码模拟了一个由 4 个路由器组成的网络,每个路由器都有若干个邻居路由器,每个路由器的初始路由表包含它的邻居路由器及其距离。在模拟过程中,每个路由器都向其邻居路由器请求路由表,并根据收到的路由表更新自己的路由表,直到收敛为止。