Untitled

 avatar
unknown
plain_text
5 months ago
1.7 kB
5
Indexable
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>

class EthernetSwitch {
private:
    std::unordered_map<std::string, int> macTable; // MAC address to port mapping
    int numPorts;

public:
    EthernetSwitch(int ports) : numPorts(ports) {}

    void learn(const std::string& macAddress, int port) {
        macTable[macAddress] = port;
        std::cout << "Learned MAC: " << macAddress << " on port: " << port << std::endl;
    }

    void forward(const std::string& srcMac, const std::string& destMac) {
        learn(srcMac, 1); // Assume source MAC is always on port 1 for simplicity
        if (macTable.find(destMac) != macTable.end()) {
            int destPort = macTable[destMac];
            std::cout << "Forwarding packet from " << srcMac << " to " << destMac << " on port: " << destPort << std::endl;
        } else {
            std::cout << "Destination MAC: " << destMac << " not found. Flooding to all ports except port 1." << std::endl;
            for (int i = 1; i <= numPorts; ++i) {
                if (i != 1) {
                    std::cout << "Flooding to port: " << i << std::endl;
                }
            }
        }
    }
};

int main() {
    EthernetSwitch mySwitch(5); // Create a switch with 5 ports

    // Simulate learning MAC addresses
    mySwitch.learn("00:11:22:33:44:55", 1);
    mySwitch.learn("66:77:88:99:AA:BB", 2);
    mySwitch.learn("CC:DD:EE:FF:00:11", 3);

    // Simulate forwarding packets
    mySwitch.forward("00:11:22:33:44:55", "66:77:88:99:AA:BB"); // Should forward to port 2
    mySwitch.forward("00:11:22:33:44:55", "AA:BB:CC:DD:EE:FF"); // Should flood

    return 0;
}
Editor is loading...
Leave a Comment