71 lines
2.0 KiB
Java
71 lines
2.0 KiB
Java
package cn.x47;
|
|
|
|
|
|
import cn.x47.config.Config;
|
|
import cn.x47.model.RIPEntry;
|
|
import cn.x47.model.RIPPacket;
|
|
import cn.x47.service.RIPClient;
|
|
import cn.x47.service.RIPServer;
|
|
|
|
import java.net.InetAddress;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.concurrent.*;
|
|
|
|
public class RIPService {
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
// 启动服务器
|
|
RIPServer server = new RIPServer();
|
|
new Thread(() -> {
|
|
try {
|
|
server.start();
|
|
} catch (InterruptedException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}).start();
|
|
|
|
// 启动客户端
|
|
RIPClient client = new RIPClient();
|
|
|
|
// 定期发送路由更新
|
|
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
|
scheduler.scheduleAtFixedRate(() -> {
|
|
RIPPacket packet = createRipResponsePacket(Config.RIP_VERSION);
|
|
client.sendRipPacket(packet);
|
|
}, 0, 30, TimeUnit.SECONDS);
|
|
|
|
// 主线程等待
|
|
Thread.currentThread().join();
|
|
}
|
|
|
|
private static RIPPacket createRipResponsePacket(byte version) {
|
|
List<RIPEntry> entries = new ArrayList<>();
|
|
|
|
try {
|
|
// 示例:添加本地路由条目
|
|
InetAddress localAddress = InetAddress.getByName("192.168.100.0");
|
|
InetAddress subnetMask = InetAddress.getByName("255.255.255.0");
|
|
InetAddress nextHop = InetAddress.getByName("192.168.123.45");
|
|
|
|
RIPEntry entry = new RIPEntry();
|
|
entry.setAddressFamily((short) 2); // AF_INET
|
|
entry.setIpAddress(localAddress);
|
|
entry.setMetric(1);
|
|
|
|
if (version == 2) {
|
|
entry.setRouteTag((short) 0);
|
|
entry.setSubnetMask(subnetMask);
|
|
entry.setNextHop(nextHop);
|
|
}
|
|
|
|
entries.add(entry);
|
|
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
}
|
|
|
|
return new RIPPacket((byte) 2, version, entries); // Command=2 (Response)
|
|
}
|
|
}
|