编程模拟路由器查找路由表的过程,用(目的地址 掩码 下一跳)的 IP 路由表以及目的地址作为输入,为目的地址查找路由表,找出正确的下一跳并输出结果。
代码很简陋,但是能用。仅供参考。
RouterSimulator.java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
public class RouterSimulator extends JFrame {
private JLabel destinationLabel, resultLabel;
private JTextField destinationField;
private JButton searchButton;
private Map<String, String> routingTable; // IP路由表
private JTable routingTableGUI;
public RouterSimulator() {
setTitle("路由器模拟器");
setSize(500, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 初始化IP路由表
routingTable = new HashMap<>();
routingTable.put("192.168.1.0/24", "192.168.1.1");
routingTable.put("10.0.0.0/8", "10.0.0.1");
routingTable.put("172.16.0.0/16", "172.16.0.1");
// 创建路由表 GUI
DefaultTableModel model = new DefaultTableModel();
model.addColumn("目的地址");
model.addColumn("掩码");
model.addColumn("下一跳");
for (String key : routingTable.keySet()) {
String[] parts = key.split("/");
String networkAddress = parts[0];
String mask = parts[1];
String nextHop = routingTable.get(key);
model.addRow(new Object[]{networkAddress, mask, nextHop});
}
routingTableGUI = new JTable(model);
JScrollPane scrollPane = new JScrollPane(routingTableGUI);
scrollPane.setPreferredSize(new Dimension(400, 120));
JPanel panel = new JPanel();
panel.add(scrollPane);
add(panel, BorderLayout.NORTH);
JPanel searchPanel = new JPanel();
destinationLabel = new JLabel("目的地址:");
destinationField = new JTextField(15);
searchButton = new JButton("查找");
resultLabel = new JLabel("");
searchPanel.add(destinationLabel);
searchPanel.add(destinationField);
searchPanel.add(searchButton);
searchPanel.add(resultLabel);
add(searchPanel, BorderLayout.CENTER);
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String destination = destinationField.getText();
String nextHop = lookupRoutingTable(destination);
if (nextHop != null) {
resultLabel.setText("下一跳:" + nextHop);
} else {
resultLabel.setText("未找到匹配的路由条目");
}
}
});
}
private String lookupRoutingTable(String destination) {
for (String key : routingTable.keySet()) {
String[] parts = key.split("/");
String networkAddress = parts[0];
int prefixLength = Integer.parseInt(parts[1]);
String[] destParts = destination.split("\\.");
String[] networkParts = networkAddress.split("\\.");
boolean match = true;
for (int i = 0; i < prefixLength / 8; i++) {
if (!destParts[i].equals(networkParts[i])) {
match = false;
break;
}
}
if (match) {
return routingTable.get(key);
}
}
return null;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
RouterSimulator simulator = new RouterSimulator();
simulator.setVisible(true);
}
});
}
}
运行截图: