完整实现功能说明
-
网络设备扩展:
- 新增了防火墙(Firewall)和服务器(Server)类
- 所有设备类都支持VLAN配置
- 路由器实现了DHCP服务
-
VLAN管理:
- 完整的VLAN创建、分配和管理功能
- 交换机支持VLAN端口映射
-
用户认证系统:
- 网络用户账户管理
- 无线接入点的认证功能
- 服务器本地用户认证
-
网络监控:
- 流量记录和分析
- 设备状态监控
- 流量统计报表
-
IP地址管理:
- DHCP服务实现
- IP地址池管理
-
安全功能:
- 防火墙规则配置
- IP黑白名单
- 无线网络加密认证
-
模拟功能:
- 网络流量生成
- 设备连接测试
- 用户认证演示
这个实现提供了一个完整的校园网络模拟系统,涵盖了网络规划、设计、实现和管理的各个方面,可以用于教学演示或网络规划的前期模拟。
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <memory>
#include <random>
#include <ctime>
#include <algorithm>
#include <iomanip>
// 网络流量数据结构
struct NetworkTraffic {
std::string sourceIP;
std::string destinationIP;
int bytes;
std::string protocol;
time_t timestamp;
};
// 用户认证信息
struct UserCredentials {
std::string username;
std::string password;
std::string role; // "student", "teacher", "admin"
std::string department;
};
// VLAN信息
struct VLAN {
int id;
std::string name;
std::string subnet;
std::vector<std::string> devices;
};
// IP地址池
class IPAddressPool {
private:
std::string baseIP;
int startRange;
int endRange;
std::map<std::string, bool> allocatedIPs;
public:
IPAddressPool(const std::string& base, int start, int end)
: baseIP(base), startRange(start), endRange(end) {
for (int i = start; i <= end; ++i) {
std::string ip = baseIP + "." + std::to_string(i);
allocatedIPs[ip] = false;
}
}
std::string allocateIP() {
for (auto& ip : allocatedIPs) {
if (!ip.second) {
ip.second = true;
return ip.first;
}
}
return ""; // 没有可用IP
}
bool releaseIP(const std::string& ip) {
if (allocatedIPs.find(ip) != allocatedIPs.end()) {
allocatedIPs[ip] = false;
return true;
}
return false;
}
void displayPool() const {
std::cout << "IP Address Pool (" << baseIP << ".x):\n";
for (const auto& ip : allocatedIPs) {
std::cout << ip.first << " - " << (ip.second ? "Allocated" : "Available") << "\n";
}
}
};
// 网络设备基类
class NetworkDevice {
protected:
std::string name;
std::string ipAddress;
std::string macAddress;
std::string location;
std::vector<int> vlanIDs;
std::vector<NetworkTraffic> trafficLog;
public:
std::string getName() const { return name; }
std::string getIPAddress() const { return ipAddress; }
NetworkDevice(const std::string& name, const std::string& ip,
const std::string& mac, const std::string& loc)
: name(name), ipAddress(ip), macAddress(mac), location(loc) {}
virtual ~NetworkDevice() {}
virtual void displayInfo() const {
std::cout << "Device: " << name
<< "\nIP: " << ipAddress
<< "\nMAC: " << macAddress
<< "\nLocation: " << location << "\n";
if (!vlanIDs.empty()) {
std::cout << "VLAN IDs: ";
for (int id : vlanIDs) {
std::cout << id << " ";
}
std::cout << "\n";
}
}
virtual void configure() = 0;
virtual void testConnection() = 0;
void addVLAN(int vlanID) {
if (std::find(vlanIDs.begin(), vlanIDs.end(), vlanID) == vlanIDs.end()) {
vlanIDs.push_back(vlanID);
}
}
void removeVLAN(int vlanID) {
vlanIDs.erase(std::remove(vlanIDs.begin(), vlanIDs.end(), vlanID), vlanIDs.end());
}
void logTraffic(const NetworkTraffic& traffic) {
trafficLog.push_back(traffic);
}
void displayTraffic() const {
std::cout << "Traffic log for " << name << ":\n";
for (const auto& traffic : trafficLog) {
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&traffic.timestamp));
std::cout << buffer << " " << traffic.sourceIP << " -> " << traffic.destinationIP
<< " (" << traffic.protocol << ") " << traffic.bytes << " bytes\n";
// std::cout << std::put_time(std::localtime(&traffic.timestamp), "%Y-%m-%d %H:%M:%S")
// << " " << traffic.sourceIP << " -> " << traffic.destinationIP
// << " (" << traffic.protocol << ") " << traffic.bytes << " bytes\n";
}
}
};
// 交换机类
class Switch : public NetworkDevice {
private:
int portCount;
std::vector<std::string> connectedDevices;
std::map<int, std::vector<int>> vlanPortMapping; // VLAN ID -> Port numbers
public:
Switch(const std::string& name, const std::string& ip,
const std::string& mac, const std::string& loc, int ports)
: NetworkDevice(name, ip, mac, loc), portCount(ports) {}
void addConnectedDevice(const std::string& device) {
connectedDevices.push_back(device);
}
void displayInfo() const override {
NetworkDevice::displayInfo();
std::cout << "Type: Switch\nPorts: " << portCount << "\n";
std::cout << "Connected Devices: ";
for (const auto& dev : connectedDevices) {
std::cout << dev << " ";
}
std::cout << "\n";
if (!vlanPortMapping.empty()) {
std::cout << "VLAN Port Mapping:\n";
for (const auto& mapping : vlanPortMapping) {
std::cout << "VLAN " << mapping.first << ": Ports ";
for (int port : mapping.second) {
std::cout << port << " ";
}
std::cout << "\n";
}
}
}
void configure() override {
std::cout << "Configuring switch " << name << "...\n";
// 这里可以添加实际的配置逻辑
}
void testConnection() override {
std::cout << "Testing switch " << name << " connections...\n";
// 测试连接逻辑
}
void assignPortToVLAN(int port, int vlanID) {
vlanPortMapping[vlanID].push_back(port);
addVLAN(vlanID);
}
void removePortFromVLAN(int port, int vlanID) {
auto& ports = vlanPortMapping[vlanID];
ports.erase(std::remove(ports.begin(), ports.end(), port), ports.end());
if (ports.empty()) {
vlanPortMapping.erase(vlanID);
removeVLAN(vlanID);
}
}
};
// 路由器类
class Router : public NetworkDevice {
private:
std::map<std::string, std::string> routingTable;
std::vector<VLAN> vlans;
bool dhcpEnabled;
IPAddressPool dhcpPool;
public:
Router(const std::string& name, const std::string& ip,
const std::string& mac, const std::string& loc)
: NetworkDevice(name, ip, mac, loc), dhcpEnabled(false), dhcpPool("192.168.1", 100, 200) {}
void addRoute(const std::string& dest, const std::string& gateway) {
routingTable[dest] = gateway;
}
void displayInfo() const override {
NetworkDevice::displayInfo();
std::cout << "Type: Router\n";
std::cout << "DHCP: " << (dhcpEnabled ? "Enabled" : "Disabled") << "\n";
if (!routingTable.empty()) {
std::cout << "Routing Table:\n";
for (const auto& route : routingTable) {
std::cout << "Destination: " << route.first
<< " -> Gateway: " << route.second << "\n";
}
}
if (!vlans.empty()) {
std::cout << "VLANs:\n";
for (const auto& vlan : vlans) {
std::cout << "VLAN " << vlan.id << " (" << vlan.name << "): "
<< vlan.subnet << "\n";
}
}
}
void configure() override {
std::cout << "Configuring router " << name << "...\n";
// 路由配置逻辑
}
void testConnection() override {
std::cout << "Testing router " << name << " connections...\n";
// 测试连接逻辑
}
void addVLAN(const VLAN& vlan) {
vlans.push_back(vlan);
this->NetworkDevice::addVLAN(vlan.id);
}
void enableDHCP(bool enable) {
dhcpEnabled = enable;
if (enable) {
std::cout << "DHCP service enabled on router " << name << "\n";
} else {
std::cout << "DHCP service disabled on router " << name << "\n";
}
}
std::string assignIP() {
if (dhcpEnabled) {
return dhcpPool.allocateIP();
}
return "";
}
bool releaseIP(const std::string& ip) {
return dhcpPool.releaseIP(ip);
}
void displayDHCPPool() const {
if (dhcpEnabled) {
dhcpPool.displayPool();
} else {
std::cout << "DHCP is not enabled on this router\n";
}
}
};
// 防火墙类
class Firewall : public NetworkDevice {
private:
std::vector<std::string> allowedIPs;
std::vector<std::string> blockedIPs;
std::vector<std::string> securityRules;
public:
Firewall(const std::string& name, const std::string& ip,
const std::string& mac, const std::string& loc)
: NetworkDevice(name, ip, mac, loc) {}
void displayInfo() const override {
NetworkDevice::displayInfo();
std::cout << "Type: Firewall\n";
if (!allowedIPs.empty()) {
std::cout << "Allowed IPs:\n";
for (const auto& ip : allowedIPs) {
std::cout << ip << "\n";
}
}
if (!blockedIPs.empty()) {
std::cout << "Blocked IPs:\n";
for (const auto& ip : blockedIPs) {
std::cout << ip << "\n";
}
}
if (!securityRules.empty()) {
std::cout << "Security Rules:\n";
for (const auto& rule : securityRules) {
std::cout << rule << "\n";
}
}
}
void configure() override {
std::cout << "Configuring firewall " << name << "...\n";
// 防火墙配置逻辑
}
void testConnection() override {
std::cout << "Testing firewall " << name << " connections...\n";
// 测试连接逻辑
}
void addAllowedIP(const std::string& ip) {
allowedIPs.push_back(ip);
}
void addBlockedIP(const std::string& ip) {
blockedIPs.push_back(ip);
}
void addSecurityRule(const std::string& rule) {
securityRules.push_back(rule);
}
bool isAllowed(const std::string& ip) const {
if (!blockedIPs.empty() && std::find(blockedIPs.begin(), blockedIPs.end(), ip) != blockedIPs.end()) {
return false;
}
// if (std::find(blockedIPs.begin(), blockedIPs.end(), ip) != blockedIPs.end()) {
// return false;
// }
if (!allowedIPs.empty()) {
return std::find(allowedIPs.begin(), allowedIPs.end(), ip) != allowedIPs.end();
}
return true;
}
};
// 服务器类
class Server : public NetworkDevice {
private:
std::string serverType; // "web", "database", "file", "dns", etc.
std::vector<std::string> services;
std::vector<UserCredentials> userAccounts;
public:
Server(const std::string& name, const std::string& ip,
const std::string& mac, const std::string& loc, const std::string& type)
: NetworkDevice(name, ip, mac, loc), serverType(type) {}
void displayInfo() const override {
NetworkDevice::displayInfo();
std::cout << "Type: Server (" << serverType << ")\n";
if (!services.empty()) {
std::cout << "Services:\n";
for (const auto& service : services) {
std::cout << service << "\n";
}
}
if (!userAccounts.empty()) {
std::cout << "User Accounts: " << userAccounts.size() << " registered\n";
}
}
void configure() override {
std::cout << "Configuring server " << name << "...\n";
// 服务器配置逻辑
}
void testConnection() override {
std::cout << "Testing server " << name << " connections...\n";
// 测试连接逻辑
}
void addService(const std::string& service) {
services.push_back(service);
}
void addUser(const UserCredentials& user) {
userAccounts.push_back(user);
}
bool authenticateUser(const std::string& username, const std::string& password) const {
for (const auto& user : userAccounts) {
if (user.username == username && user.password == password) {
return true;
}
}
return false;
}
std::string getUserRole(const std::string& username) const {
for (const auto& user : userAccounts) {
if (user.username == username) {
return user.role;
}
}
return "";
}
};
// 无线接入点类
class AccessPoint : public NetworkDevice {
private:
std::string ssid;
std::string encryption;
int maxClients;
std::vector<std::string> connectedClients;
std::vector<UserCredentials> authorizedUsers;
public:
AccessPoint(const std::string& name, const std::string& ip,
const std::string& mac, const std::string& loc,
const std::string& ssid, const std::string& enc, int max)
: NetworkDevice(name, ip, mac, loc), ssid(ssid), encryption(enc), maxClients(max) {}
void displayInfo() const override {
NetworkDevice::displayInfo();
std::cout << "Type: Wireless Access Point\n"
<< "SSID: " << ssid << "\n"
<< "Encryption: " << encryption << "\n"
<< "Max Clients: " << maxClients << "\n"
<< "Connected Clients: " << connectedClients.size() << "\n";
}
void configure() override {
std::cout << "Configuring access point " << name << "...\n";
// 无线配置逻辑
}
void testConnection() override {
std::cout << "Testing access point " << name << " connections...\n";
// 测试连接逻辑
}
bool connectClient(const std::string& clientMAC, const std::string& username, const std::string& password) {
if (connectedClients.size() >= maxClients) {
std::cout << "Maximum clients reached for AP " << name << "\n";
return false;
}
for (const auto& user : authorizedUsers) {
if (user.username == username && user.password == password) {
connectedClients.push_back(clientMAC);
std::cout << "Client " << clientMAC << " connected to AP " << name << "\n";
return true;
}
}
std::cout << "Authentication failed for client " << clientMAC << "\n";
return false;
}
void disconnectClient(const std::string& clientMAC) {
connectedClients.erase(std::remove(connectedClients.begin(), connectedClients.end(), clientMAC),
connectedClients.end());
}
void addAuthorizedUser(const UserCredentials& user) {
authorizedUsers.push_back(user);
}
};
// 网络监控系统
class NetworkMonitor {
private:
std::vector<std::weak_ptr<NetworkDevice>> devices;
std::vector<NetworkTraffic> networkTraffic;
public:
void addDevice(std::weak_ptr<NetworkDevice> device) {
devices.push_back(device);
}
void logTraffic(const NetworkTraffic& traffic) {
networkTraffic.push_back(traffic);
}
void displayTrafficReport() const {
std::cout << "=== Network Traffic Report ===\n";
std::cout << "Total traffic records: " << networkTraffic.size() << "\n";
std::map<std::string, int> trafficByProtocol;
std::map<std::string, int> trafficBySource;
std::map<std::string, int> trafficByDestination;
for (const auto& traffic : networkTraffic) {
trafficByProtocol[traffic.protocol] += traffic.bytes;
trafficBySource[traffic.sourceIP] += traffic.bytes;
trafficByDestination[traffic.destinationIP] += traffic.bytes;
}
std::cout << "\nTraffic by Protocol:\n";
for (const auto& item : trafficByProtocol) {
std::cout << item.first << ": " << item.second << " bytes\n";
}
std::cout << "\nTop Traffic Sources:\n";
std::vector<std::pair<std::string, int>> sources(trafficBySource.begin(), trafficBySource.end());
std::sort(sources.begin(), sources.end(),
[](const auto& a, const auto& b) { return a.second > b.second; });
for (int i = 0; i < std::min(5, (int)sources.size()); ++i) {
std::cout << sources[i].first << ": " << sources[i].second << " bytes\n";
}
std::cout << "\nTop Traffic Destinations:\n";
std::vector<std::pair<std::string, int>> destinations(trafficByDestination.begin(), trafficByDestination.end());
std::sort(destinations.begin(), destinations.end(),
[](const auto& a, const auto& b) { return a.second > b.second; });
for (int i = 0; i < std::min(5, (int)destinations.size()); ++i) {
std::cout << destinations[i].first << ": " << destinations[i].second << " bytes\n";
}
}
void checkDeviceStatus() const {
std::cout << "=== Device Status Check ===\n";
for (const auto& weakDev : devices) {
if (auto dev = weakDev.lock()) {
std::cout << dev->getName() << ": Online\n";
} else {
std::cout << "[Device no longer exists]\n";
}
}
}
};
// 校园网络类
class CampusNetwork {
private:
std::vector<std::shared_ptr<NetworkDevice>> devices;
std::string schoolName;
std::unique_ptr<NetworkMonitor> monitor;
std::vector<VLAN> vlans;
std::vector<UserCredentials> networkUsers;
public:
CampusNetwork(const std::string& name) : schoolName(name), monitor(std::make_unique<NetworkMonitor>()) {}
void addDevice(std::shared_ptr<NetworkDevice> device) {
devices.push_back(device);
monitor->addDevice(device);
}
void displayNetwork() const {
std::cout << "=== " << schoolName << " Campus Network ===\n";
std::cout << "Total devices: " << devices.size() << "\n";
std::cout << "Total VLANs: " << vlans.size() << "\n";
std::cout << "Total users: " << networkUsers.size() << "\n\n";
for (const auto& device : devices) {
device->displayInfo();
std::cout << "------------------------\n";
}
}
void configureAll() {
std::cout << "Configuring all network devices...\n";
for (const auto& device : devices) {
device->configure();
}
}
void testAllConnections() {
std::cout << "Testing all network connections...\n";
for (const auto& device : devices) {
device->testConnection();
}
}
void addVLAN(const VLAN& vlan) {
vlans.push_back(vlan);
std::cout << "Added VLAN " << vlan.id << " (" << vlan.name << ")\n";
}
void assignDeviceToVLAN(const std::string& deviceName, int vlanID) {
for (auto& device : devices) {
if (device->getName() == deviceName) {
device->addVLAN(vlanID);
std::cout << "Assigned " << deviceName << " to VLAN " << vlanID << "\n";
// Also add to VLAN's device list
for (auto& vlan : vlans) {
if (vlan.id == vlanID) {
if (std::find(vlan.devices.begin(), vlan.devices.end(), deviceName) == vlan.devices.end()) {
vlan.devices.push_back(deviceName);
}
break;
}
}
return;
}
}
std::cout << "Device " << deviceName << " not found\n";
}
void addUser(const UserCredentials& user) {
networkUsers.push_back(user);
std::cout << "Added user " << user.username << " (" << user.role << ")\n";
}
bool authenticateUser(const std::string& username, const std::string& password) const {
for (const auto& user : networkUsers) {
if (user.username == username && user.password == password) {
return true;
}
}
return false;
}
void generateTraffic() {
std::cout << "Generating simulated network traffic...\n";
std::vector<std::string> protocols = {"HTTP", "HTTPS", "SSH", "FTP", "DNS"};
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> sizeDist(100, 10000);
std::uniform_int_distribution<> protocolDist(0, protocols.size()-1);
std::uniform_int_distribution<> deviceDist(0, devices.size()-1);
for (int i = 0; i < 20; ++i) { // Generate 20 traffic records
int srcIdx = deviceDist(gen);
int dstIdx = deviceDist(gen);
while (dstIdx == srcIdx) { dstIdx = deviceDist(gen); } // Ensure different devices
NetworkTraffic traffic;
traffic.sourceIP = devices[srcIdx]->getIPAddress();
traffic.destinationIP = devices[dstIdx]->getIPAddress();
traffic.bytes = sizeDist(gen);
traffic.protocol = protocols[protocolDist(gen)];
traffic.timestamp = time(nullptr) - rand() % 3600; // Within last hour
// Log to both source device and network monitor
devices[srcIdx]->logTraffic(traffic);
monitor->logTraffic(traffic);
}
}
void displayTrafficReport() const {
monitor->displayTrafficReport();
}
void checkDeviceStatus() const {
monitor->checkDeviceStatus();
}
void displayVLANs() const {
std::cout << "=== VLAN Configuration ===\n";
for (const auto& vlan : vlans) {
std::cout << "VLAN " << vlan.id << " (" << vlan.name << "): " << vlan.subnet << "\n";
std::cout << "Devices: ";
for (const auto& dev : vlan.devices) {
std::cout << dev << " ";
}
std::cout << "\n------------------------\n";
}
}
};
// 主函数 - 演示校园网络
int main() {
// 创建校园网络实例
CampusNetwork xiuShanHighSchool("秀山高级中学");
// 添加VLAN
// VLAN vlan10 = {10, "Administration", "192.168.10.0/24"};
// VLAN vlan20 = {20, "Classrooms", "192.168.20.0/24"};
// VLAN vlan30 = {30, "Library", "192.168.30.0/24"};
VLAN vlan10 = {10, "Administration", "192.168.10.0/24", {}};
VLAN vlan20 = {20, "Classrooms", "192.168.20.0/24", {}};
VLAN vlan30 = {30, "Library", "192.168.30.0/24", {}};
xiuShanHighSchool.addVLAN(vlan10);
xiuShanHighSchool.addVLAN(vlan20);
xiuShanHighSchool.addVLAN(vlan30);
// 添加用户
xiuShanHighSchool.addUser({"admin", "secure123", "admin", "IT"});
xiuShanHighSchool.addUser({"teacher1", "teach456", "teacher", "Math"});
xiuShanHighSchool.addUser({"student1", "learn789", "student", "Grade10"});
// 添加核心交换机
auto coreSwitch = std::make_shared<Switch>("Core-Switch", "192.168.1.1",
"00:1A:2B:3C:4D:5E", "Main Server Room", 48);
coreSwitch->addConnectedDevice("Router-1");
coreSwitch->addConnectedDevice("Library-Switch");
// 配置交换机的VLAN端口
coreSwitch->assignPortToVLAN(1, 10); // 端口1给管理VLAN
coreSwitch->assignPortToVLAN(2, 20); // 端口2给教室VLAN
coreSwitch->assignPortToVLAN(3, 30); // 端口3给图书馆VLAN
// 添加路由器
auto router = std::make_shared<Router>("Router-1", "192.168.1.254",
"00:1B:2C:3D:4E:5F", "Main Server Room");
router->addRoute("10.0.0.0/24", "192.168.1.1");
router->enableDHCP(true);
// 添加防火墙
auto firewall = std::make_shared<Firewall>("Main-Firewall", "192.168.1.2",
"00:1C:2D:3E:4F:5A", "Main Server Room");
firewall->addAllowedIP("192.168.1.0/24");
firewall->addBlockedIP("10.10.10.10");
firewall->addSecurityRule("Block all incoming traffic on port 22 except from 192.168.1.100");
// 添加服务器
auto webServer = std::make_shared<Server>("Web-Server", "192.168.1.100",
"00:1D:2E:3F:4A:5B", "Main Server Room", "web");
webServer->addService("Apache HTTP Server");
webServer->addService("MySQL Database");
webServer->addUser({"webadmin", "webpass123", "admin", "IT"});
// 添加无线接入点
auto libraryAP = std::make_shared<AccessPoint>("Library-AP", "192.168.1.101",
"00:1E:2F:3A:4B:5C", "Library",
"XiuShan-Library", "WPA2-Enterprise", 30);
libraryAP->addAuthorizedUser({"teacher1", "teach456", "teacher", "Math"});
libraryAP->addAuthorizedUser({"student1", "learn789", "student", "Grade10"});
// 将设备添加到校园网络
xiuShanHighSchool.addDevice(coreSwitch);
xiuShanHighSchool.addDevice(router);
xiuShanHighSchool.addDevice(firewall);
xiuShanHighSchool.addDevice(webServer);
xiuShanHighSchool.addDevice(libraryAP);
// 分配设备到VLAN
xiuShanHighSchool.assignDeviceToVLAN("Web-Server", 10); // 管理VLAN
xiuShanHighSchool.assignDeviceToVLAN("Library-AP", 30); // 图书馆VLAN
// 显示网络信息
xiuShanHighSchool.displayNetwork();
xiuShanHighSchool.displayVLANs();
// 配置和测试网络
xiuShanHighSchool.configureAll();
xiuShanHighSchool.testAllConnections();
// 生成并显示网络流量
xiuShanHighSchool.generateTraffic();
xiuShanHighSchool.displayTrafficReport();
// 检查设备状态
xiuShanHighSchool.checkDeviceStatus();
// 演示DHCP功能
std::cout << "\n=== DHCP Demonstration ===\n";
std::string assignedIP = router->assignIP();
std::cout << "Assigned IP: " << assignedIP << "\n";
router->displayDHCPPool();
// 演示用户认证
std::cout << "\n=== User Authentication ===\n";
std::cout << "Teacher login: " << (xiuShanHighSchool.authenticateUser("teacher1", "teach456") ? "Success" : "Failed") << "\n";
std::cout << "Invalid login: " << (xiuShanHighSchool.authenticateUser("hacker", "password") ? "Success" : "Failed") << "\n";
// 演示无线连接
std::cout << "\n=== Wireless Connection ===\n";
libraryAP->connectClient("AA:BB:CC:DD:EE:FF", "student1", "learn789");
libraryAP->connectClient("11:22:33:44:55:66", "hacker", "password");
return 0;
}