1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
#include <iostream> #include <vector> #include <string> #include <cstdlib> #include <ctime> class Frame { public: Frame(const std::string& data) : data(data) { checksum = calculateChecksum(data); } std::string getData() const { return data; } int getChecksum() const { return checksum; } bool isCorrupted() const { return calculateChecksum(data) != checksum; } private: std::string data; int checksum; int calculateChecksum(const std::string& data) const { int sum = 0; for (char c : data) { sum += static_cast<int>(c); } return sum % 256; // Simple checksum (mod 256) } }; class DataLinkLayer { public: void sendFrame(const Frame& frame) { std::cout << "Sending frame with data: " << frame.getData() << std::endl; receivedFrame = frame; } void receiveFrame() { if (receivedFrame.isCorrupted()) { std::cout << "Error: Frame is corrupted." << std::endl; } else { std::cout << "Frame received successfully with data: " << receivedFrame.getData() << std::endl; } } private: Frame receivedFrame{"default"}; }; int main() { std::srand(std::time(0)); DataLinkLayer linkLayer; // Simulate sending a frame std::string data = "Hello, Data Link Layer!"; Frame frame(data); linkLayer.sendFrame(frame); // Simulate potential corruption if (std::rand() % 2) { // Simulate corruption by altering data std::string corruptedData = data; corruptedData[0] = (corruptedData[0] == 'H') ? 'X' : 'H'; // Simple corruption example Frame corruptedFrame(corruptedData); linkLayer.sendFrame(corruptedFrame); } // Receive and check the frame linkLayer.receiveFrame(); return 0; } |
Explanation
- Header Files:
<iostream>
: For input and output operations.<vector>
: Used here just for completeness in case of extension.<string>
: To handle string operations.<cstdlib>
: For functions likestd::rand()
.<ctime>
: For seeding the random number generator.
- Frame Class:
- Constructor: Initializes a frame with data and calculates its checksum.
- getData(): Returns the data of the frame.
- getChecksum(): Returns the checksum of the frame.
- isCorrupted(): Checks if the frame has been corrupted by comparing the calculated checksum with the stored checksum.
- calculateChecksum(): Computes a simple checksum by summing ASCII values of characters in the data and taking modulo 256.
- DataLinkLayer Class:
- sendFrame(): Simulates sending a frame by storing it in
receivedFrame
. - receiveFrame(): Checks the received frame for corruption and outputs the result.
- sendFrame(): Simulates sending a frame by storing it in
- main() Function:
- Seeds the random number generator.
- Creates an instance of
DataLinkLayer
. - Creates a frame with some data and sends it.
- Simulates potential corruption by altering the frame’s data.
- Receives and checks the frame to detect any corruption.