<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Miha_S on Medium]]></title>
        <description><![CDATA[Stories by Miha_S on Medium]]></description>
        <link>https://medium.com/@mishastatnik?source=rss-efbd1fc5fbc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fVSMh2t41hCziNH5</url>
            <title>Stories by Miha_S on Medium</title>
            <link>https://medium.com/@mishastatnik?source=rss-efbd1fc5fbc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:45:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mishastatnik/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TCP/IP. Data Link Layer. Part 3]]></title>
            <link>https://medium.com/@mishastatnik/tcp-ip-data-link-layer-part-3-ad0e66ae472d?source=rss-efbd1fc5fbc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad0e66ae472d</guid>
            <category><![CDATA[data-link-layer]]></category>
            <category><![CDATA[ethernet-switch]]></category>
            <category><![CDATA[ethernet]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[tcp-ip]]></category>
            <dc:creator><![CDATA[Miha_S]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 21:54:55 GMT</pubDate>
            <atom:updated>2025-09-24T21:54:55.393Z</atom:updated>
            <content:encoded><![CDATA[<p>In this chapter, I want to present the most widely used Data Link Layer protocol today: <strong>Ethernet</strong>.</p><h3>History</h3><p><strong>Ethernet</strong> is a bit more complex than the Point-to-Point Protocol we looked at in the previous chapter. Initially, Ethernet was designed as a bus that spanned an entire building, where any device could connect and attempt to transmit data. Because of this, two more problems arose:</p><ol><li>The protocol needed a way to specify <strong>the destination address</strong>, so that devices on the bus knew which data was meant for them.</li><li>A mechanism to <strong>coordinate access</strong> to the shared medium was required to avoid collisions from simultaneous transmissions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*AyZZxHVX3D8M-VM-D1ehkQ.png" /><figcaption>Ethernet bus.</figcaption></figure><p>The solution to selecting the destination was pretty straightforward. The address of the device was simply included in the <strong>protocol header</strong>. And when a device on the bus receive a message, it check whether destination is this device. In case it is this device, it accepted the frame, otherwise just discarded it. This address is called the MAC (Media Access Control) address, and you may have heard of it before. Each network interface in the world is supposed to have a <strong>unique</strong> MAC address.</p><p>A mechanism to coordinate simultaneous transmission is more complex. Early Ethernet solved this problem using a method called <strong>CSMA/CD</strong> (Carrier Sense Multiple Access with Collision Detection). The idea was simple: before sending data, a device would first “listen” to the bus (carrier sense). If the medium was free, it would start transmitting (multiple access). However, if two devices transmitted at the same time, a collision would occur. In that case, both devices would stop, wait for a random period of time, and then try again (collision detection).</p><p>This approach worked well for the original shared-bus Ethernet. But with the growth of networks and the introduction of switches, modern Ethernet no longer relies on collisions — each link is point-to-point, so CSMA/CD is essentially obsolete. We will return to switches in the end of this chapter.</p><h3>Protocol Frame</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7fpBB39N-somcxnLzV_4Q.png" /><figcaption>Ethernet protocol frame</figcaption></figure><p>Ethernet protocol frame starts with a <strong>Preamble</strong> of 7 bytes, each with the bit pattern 10101010, used to synchronize clocks. It is followed by the <strong>Start Frame Delimiter (SFD)</strong> of 1 byte with the value 10101011, which marks the beginning of the actual frame.</p><p>Next comes the <strong>Destination MAC Address</strong> (6 bytes) and the <strong>Source MAC Address</strong> (6 bytes). The first bit of the destination address determines whether it is an individual address (0) or a group address (1). Group addresses allow multiple stations to listen to the same address. The special case of all 1 bits is the <strong>broadcast address</strong>, where all stations on the LAN will receive the frame.</p><p>After the addresses comes the <strong>Type field</strong> (2 bytes), which specifies the higher-level protocol contained in the payload (for example, IPv4, ARP, or IPv6). This is necessary because multiple network-layer protocols can be used on the same machine.</p><p>Then comes the <strong>Data and Padding</strong>. The Data field must be at least 46 bytes and at most 1500 bytes. If the actual payload is smaller than 46 bytes, padding is added to reach the minimum size requirement.</p><p>Finally, the frame ends with the <strong>Frame Check Sequence (FCS)</strong>, which is a 4-byte CRC value used to detect errors in transmission.</p><p>In the modern IEEE 802.3 Ethernet frame, the 2-byte field after the source address is not a Type field but a <strong>Length field</strong>, telling how many bytes of payload follow. The information about which protocol is carried is moved into the <strong>data itself</strong>.</p><h3>Switched Ethernet</h3><p>Ethernet soon began to evolve away from the single cable architecture of classic Ethernet. In the original design, all stations shared the same medium, so only one could transmit at a time, and collisions were handled with CSMA/CD. As networks grew, this approach became a bottleneck.</p><p>Switched Ethernet replaced the shared medium with a <strong>switch</strong>, a device that connects each station through a dedicated point-to-point link. This eliminates collisions, since each link is used by only one sender and one receiver at a time. It also allows <strong>full-duplex communication</strong>, where data can flow simultaneously in both directions.</p><p>Another major change is that each port on the switch forms its own <strong>collision domain</strong>. On a single link, there are now only two participants: the switch and the device connected to it. This eliminates the need to handle collisions from multiple stations. When the switch receives an Ethernet frame, it reads the <strong>destination MAC address</strong> and uses its <strong>forwarding table</strong> to determine the correct output port to which the frame should be redirected. If the destination is unknown, the switch floods the frame to all ports except the one it came from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqZsZZ3lauEpelo_iaLhog.png" /><figcaption>Ethernet switch</figcaption></figure><h3>Wrapping Up</h3><p>That’s all for this brief overview of Ethernet. It has many more peculiarities — such as VLAN tagging, spanning tree protocol, and jumbo frames — but we will not touch them in this series. In the next chapter, we will move one step up the hierarchy: the <strong>network layer</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0e66ae472d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP/IP. Data Link layer. Part 2]]></title>
            <link>https://medium.com/@mishastatnik/tcp-ip-data-link-layer-part-2-7d30917d7015?source=rss-efbd1fc5fbc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d30917d7015</guid>
            <category><![CDATA[transmission]]></category>
            <category><![CDATA[data-link-layer]]></category>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Miha_S]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 15:45:07 GMT</pubDate>
            <atom:updated>2025-08-22T15:45:07.587Z</atom:updated>
            <content:encoded><![CDATA[<p>Physical layer, data link layer and network layer are independent processes that communicate by passing messages back and forth. The physical layer process and some of the data link layer process run on dedicated hardware called a <strong>NIC (Network Interface Card)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1Q0V3_SJcH5FCWfipOaFA.png" /><figcaption>Organization of layers. (Picture by author)</figcaption></figure><p>The rest of the link layer process and network layer process run on the main CPU as part of the operating system, with the software for link layer often taking the form of a driver.</p><p>Here are thing for which hardware part is usually responsible in Data Link layer:</p><ul><li>Framing logic</li><li>Byte stuffing and unstuffing</li><li>Calculating and checking error codes</li></ul><p>So in our implementation, we’ll assume that all of these low-level functions are handled by the hardware part of the data link layer. That lets us focus on the remaining responsibilities.</p><h3>Naive data link protocol</h3><p>I’ll be presenting the protocol example using <strong>C++</strong>. Normally, low-level functionalities like this are written in <strong>C</strong> for maximum control and performance. However, I’ll use C++ here because its syntax is a bit more expressive and readable for demonstration purposes. I’ll also intentionally skip most language-level optimizations so we can focus entirely on the protocol logic itself, without getting distracted by micro-level tuning.</p><p>Here are some predefined types and methods we will be using:</p><pre>using Packet = vector&lt;byte&gt;;<br>using uint = unsigned int;<br><br>enum FrameType {<br>    Data,<br>    Acknowledgment,<br>    NotAcknowledged<br>};<br><br>struct Frame {<br>    uint sequenceNumber;<br>    uint acknowledgmentNumber;<br>    FrameType type;<br>    Packet packet;<br>};<br><br>enum EventType {<br>    FrameArrival,<br>    Timeout,<br>    ChecksumError<br>};<br><br>Packet fromNetworkLayer();<br>void toNetworkLayer(Packet packet);<br><br>void toPhysicalLayer(Frame frame);<br>Frame fromPhysicalLayer();<br><br>EventType waitForEvent();</pre><p>For now we will assume following things:</p><ul><li>Network layer always has packets for us to send, so fromNetworkLayer always gives us new packet to send.</li><li>toNetworkLayer transmits received packet to network layer.</li><li>toPhysicalLayer passes our frame to the hardware, where is is appended with error code, stuffed and framed, and sent to the other device.</li><li>fromPhysicalLayer gives us received frame; in case there are no frames, the method blocks.</li><li>waitForEvent this function blocks, until one of predefined events happens.</li></ul><p>And here goes naive data link protocol, without any rate or errors handling, and flow of data only in one direction:</p><pre>void sender() {<br>    while(true) {<br>        Packet packet = fromNetworkLayer();         // Get packet from network layer<br>        Frame frameToSend;                          // Create frame to send<br>        frameToSend.packet = packet;                // Set packet in frame<br>        toPhysicalLayer(frameToSend);               // Send frame to physical layer<br>        EventType event = waitForEvent();           // Do not proceed until acknowledgment frame arrives<br>    }<br>}<br><br>void receiver() {<br>    while(true) {<br>        waitForEvent();                             // Wait for an event indicating a frame arrival<br>        Frame receivedFrame = fromPhysicalLayer();  // Get the received frame from the physical layer<br>        toNetworkLayer(receivedFrame.packet);       // Deliver the packet to the network layer<br>        toPhysicalLayer(Frame{});                   // Send a dummy frame to acknowledge receipt<br>    }<br>}</pre><p>For this example, we have assumed that the communication channel is <strong>error-free</strong>. The focus here is on demonstrating a simple form of <strong>flow control</strong>, ensuring the sender doesn’t overwhelm the receiver.<br>The rule is straightforward: after sending a frame, the sender must wait until it receives a dummy frame from the receiver. This dummy frame acts as an <strong>acknowledgment</strong> that the previous frame was received successfully, and as a signal that the sender may proceed with sending the next frame.</p><h3>Error control</h3><p>A frame can be damaged in transit, in which case its checksum will be incorrect. Or it can be lost entirely. To handle these problems, we can use the following protocol:</p><ul><li>If a frame arrives intact, the receiver accepts it and sends back an <strong>acknowledgment frame</strong>.</li><li>If the frame is damaged or never arrives, no acknowledgment is sent. The sender runs a timer, and if the acknowledgment hasn’t arrived within the set time, it will resend the frame.</li></ul><p>There’s one complication: the acknowledgment frame itself can also be lost. In that case, the sender would retransmit the same frame, and the receiver might pass this duplicate frame up to the network layer a second time.</p><p>To avoid that, we add <strong>sequence numbers</strong> to frames. The receiver keeps track of the sequence number it expects. If the incoming frame has the expected number, it’s accepted, acknowledged, and the expected number is incremented. If the frame’s sequence number matches the <strong>previously received</strong> frame, the receiver knows it’s a duplicate — it still sends an acknowledgment but discards the data, preventing it from being delivered twice.</p><p>Firstly we introduce few new functions:</p><pre>void startTimer(uint seqNum);<br>void stopTimer(uint seqNum);<br><br>#define MAX_SEQ_NUM 1<br><br>uint inc(const uint &amp;x)<br>{<br>    return (x + 1) % MAX_SEQ_NUM; // Increment x and wrap around at MAX_SEQ_NUM<br>}<br><br>uint dec(const uint &amp;x)<br>{<br>    return (x - 1 + MAX_SEQ_NUM) % MAX_SEQ_NUM; // Decrement x and wrap around at MAX_SEQ_NUM<br>}<br><br><br>Frame buildFrame(uint seqNum, uint acknowledgmentNumber, const Packet &amp;packet)<br>{<br>    Frame frame;<br>    frame.sequenceNumber = seqNum;<br>    frame.acknowledgmentNumber = acknowledgmentNumber;<br>    frame.packet = packet;<br>    return frame;<br>}</pre><p>inc increments number in a cycle manner, with cycle of size MAX_SEQ_NUM. While dec decreases number in the same manner. For this algorithm, MAX_SEQ_NUM of 1 is enough. (to distinguish between currently sending frame, and next frame).</p><pre>void sender()<br>{<br>    uint nextFrameToSendNum = 0;<br><br>    Frame nextFrameToSend = buildFrame(nextFrameToSendNum, 0, fromNetworkLayer());<br>    toPhysicalLayer(nextFrameToSend);<br>    startTimer(nextFrameToSendNum);<br><br>    while (true)<br>    {<br>        EventType event = waitForEvent();<br><br>        if (event == FrameArrival)<br>        {<br>            Frame receivedFrame = fromPhysicalLayer();<br>            if (receivedFrame.acknowledgmentNumber == nextFrameToSendNum)<br>            {<br>                stopTimer(nextFrameToSendNum);<br>                nextFrameToSendNum = inc(nextFrameToSendNum);<br>                nextFrameToSend = buildFrame(nextFrameToSendNum, 0, fromNetworkLayer());<br>            }<br>        }<br><br>        // If event wasn&#39;t FrameArrival, it could be Timeout or ChecksumError<br>        // So we resend the same frame.<br>        toPhysicalLayer(nextFrameToSend);<br>        startTimer(nextFrameToSendNum);<br>    }<br>}</pre><pre>void receiver()<br>{<br>    uint expectedFrameNum = 0;<br><br>    while (true)<br>    {<br>        EventType event = waitForEvent();<br><br>        if (event == FrameArrival)<br>        {<br>            Frame receivedFrame = fromPhysicalLayer();<br>            if (receivedFrame.sequenceNumber == expectedFrameNum)<br>            {<br>                toNetworkLayer(receivedFrame.packet);<br>                toPhysicalLayer(buildFrame(0, expectedFrameNum, Packet{}));<br>                expectedFrameNum = inc(expectedFrameNum);<br>            }<br>            else<br>            {<br>                // If the frame is not the expected one, send Acknowledgment for the last received frame<br>                toPhysicalLayer(buildFrame(0, dec(expectedFrameNum), Packet{}));<br>            }<br>        }<br>    }<br>}</pre><h3>Bidirectional transfer</h3><p>So far, we’ve been looking at the receiver and sender as if they were implemented separately. In practice, that’s not how it works — the two roles are usually combined in a single protocol entity. So let’s unify them.</p><p>Earlier, we saw that the receiver sends an acknowledgment (ACK) frame back to the sender to confirm that a frame was received successfully. But sending a <strong>separate frame only for acknowledgment</strong> is wasteful in terms of bandwidth. There’s a smarter way.</p><p>Instead of sending acknowledgments on their own, we can <strong>embed the acknowledgment number inside the next outgoing data frame</strong>. This technique is called <em>piggybacking</em>. It helps reduce overhead, since one frame now serves both purposes: carrying new data and confirming receipt of the previous one.</p><p>However, there’s a catch: what if the receiver has no data to send back for a while? In that case, it can’t just wait indefinitely. To solve this, a timer is used. If no data frame is ready within a certain period, the receiver will still send a standalone acknowledgment (sometimes called a <strong>pure ACK</strong>) to prevent the sender from thinking the frame was lost. In our protocol, we will send acknowledgment together with last packet, that we were sending, assuming that receiver didn’t get one.</p><pre>void protocol()<br>{<br>    uint expectedFrameNum = 0;<br>    uint nextFrameToSendNum = 0;<br><br>    Packet bufferedPacket = fromNetworkLayer();<br>    Frame nextFrameToSend = buildFrame(nextFrameToSendNum, dec(expectedFrameNum), bufferedPacket);<br>    toPhysicalLayer(nextFrameToSend);<br>    startTimer(nextFrameToSendNum);<br><br>    while (true)<br>    {<br>        EventType event = waitForEvent();<br>        if (event == FrameArrival)<br>        {<br>            Frame receivedFrame = fromPhysicalLayer();<br><br>            if (receivedFrame.sequenceNumber == expectedFrameNum)<br>            {<br>                toNetworkLayer(receivedFrame.packet);<br>                expectedFrameNum = inc(expectedFrameNum);<br>            }<br><br>            if (receivedFrame.acknowledgmentNumber == nextFrameToSendNum)<br>            {<br>                stopTimer(nextFrameToSendNum);<br>                bufferedPacket = fromNetworkLayer();<br>                nextFrameToSendNum = inc(nextFrameToSendNum);<br>            }<br>        }<br><br>        nextFrameToSend = buildFrame(nextFrameToSendNum, dec(expectedFrameNum), bufferedPacket);<br>        toPhysicalLayer(nextFrameToSend);<br>        startTimer(nextFrameToSendNum);<br>    }<br>}</pre><h3>Sliding window protocol</h3><p>So far, we’ve been assuming that only <strong>one frame at a time</strong> can be sent and acknowledged before moving on to the next. This approach works, but it’s far from efficient — the sender spends a lot of time just waiting for acknowledgments instead of actually sending data.</p><p>That’s where the <strong>sliding window protocol</strong> comes in.</p><p>In this method, the sender doesn’t stop after transmitting one frame. Instead, it can send <strong>multiple frames in sequence</strong> before waiting for an acknowledgment. How many frames exactly? That’s controlled by the <strong>window size</strong>.</p><ul><li>If the window size is <strong>1</strong>, we’re basically back to Stop-and-Wait (the most basic protocol).</li><li>If the window size is larger (say 4), the sender can transmit 4 frames in a row, and then it only needs to pause once the window is “full.”</li></ul><p>As acknowledgments come in, the “window” slides forward, freeing up space for new frames to be sent.</p><p><strong>But what if a frame gets lost?</strong></p><p>Here’s where things get interesting. Depending on how retransmissions are handled, there are two main variants:</p><ul><li><strong>Go-Back-N (GBN):</strong> If one frame is lost or damaged, the receiver discards everything after it, and the sender must retransmit from that lost frame onward.</li><li><strong>Selective Repeat (SR):</strong> The receiver can accept and buffer frames that arrive after the missing one. Only the lost frame needs to be retransmitted.</li></ul><p>Selective Repeat is more efficient, but it’s also more complex to implement.<br>We will skip implementations of these more advanced protocols.</p><h3>Wrapping Up</h3><p>In this part, we started with the simplest possible protocol — one frame at a time, with a dummy acknowledgment — and gradually added reliability with sequence numbers and timers. Then we combined sending and receiving into a single process with piggybacking, and finally introduced the <strong>sliding window protocol</strong>, which is the foundation of efficient, real-world data link communication.</p><p>In the next part we will take a look at real life Link Layer protocols.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d30917d7015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP/IP. Data Link layer. Part 1]]></title>
            <link>https://medium.com/@mishastatnik/tcp-ip-data-link-layer-part-1-a886860b993e?source=rss-efbd1fc5fbc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a886860b993e</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[tcp-ip]]></category>
            <category><![CDATA[framing]]></category>
            <category><![CDATA[data-link-layer]]></category>
            <category><![CDATA[error-detection]]></category>
            <dc:creator><![CDATA[Miha_S]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 19:15:15 GMT</pubDate>
            <atom:updated>2025-08-02T19:15:15.681Z</atom:updated>
            <content:encoded><![CDATA[<p>So, we already have the physical layer — that’s the one responsible for transmitting raw streams of bits between devices. Now we move up to the data link layer. This layer builds on top of the physical layer and offers a new kind of service: <em>the unreliable delivery of packets of data(from upper layer) to the next directly connected device.</em></p><p>In other words, the data link layer takes a chunk of data from the layer above, wraps it in a <strong>frame</strong>, and tries to pass it to the next hop on the network. But — and this is important — it doesn’t guarantee anything. No promise that the frame will actually arrive. No guarantee that it won’t get duplicated, arrive out of order, or even be corrupted along the way. At this level, anything can happen.</p><p>But that’s just the basic contract of the data link layer. In reality, some protocols go beyond this minimal service and offer limited guarantees when it comes to delivering packets from the upper layer. While the data link layer <em>can</em> be unreliable by design, many real-world protocols introduce mechanisms like error detection, retransmission, or duplicate suppression to improve delivery. So depending on the specific protocol in use, you might get a more reliable experience — just don’t count on it in upper layer.</p><h3>Frame boundary detection</h3><p>Let’s start with the fundamental problem the data link layer needs to solve: how to separate chunks of data — called <strong>frames</strong> — as they travel over a raw bit stream.</p><p>There are several reasons why breaking up data into frames is more than just a technical detail:</p><ul><li><strong>Error control</strong> — Framing makes it possible to attach a checksum or other error-detection code to each unit of data. If a frame gets corrupted in transit, only that frame needs to be resent — not the entire file or stream.</li><li><strong>Flow control</strong> — Receivers may not always be ready to handle a huge stream of data all at once. Smaller, manageable frames allow the receiver to keep up, pause reception, or signal congestion when needed.</li><li><strong>Metadata and control info</strong> — Frames can carry more than just payload data. Headers can include useful metadata — like MAC addresses, payload size, or even protocol-specific commands — that help with routing, processing, and coordination.</li></ul><p>There may be other reasons too, but the ones listed above are more than enough to justify why data should be divided into frames.</p><p>So, how do we detect the start and end of frames in a continuous stream of bytes? The most common approach is to use special <strong>flag bytes</strong> that mark the beginning and end of each frame. For example, the byte 0x7E is often used as a frame delimiter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*K2rGkA2nBtWCWU2VYWcwMg.png" /><figcaption>Delimiting data with flag bytes. (picture by author)</figcaption></figure><p>That way, the receiver can scan the incoming byte stream and easily recognize where each frame starts and ends — everything between two 0x7E bytes is treated as one complete frame. Simple and effective.</p><p>But this raises an important question: what happens if the actual data inside the frame contains the same special byte? Without a fix, the receiver would get confused, thinking the frame ended prematurely.</p><p>The solution is <strong>byte stuffing</strong>. Whenever the sender’s data contains a byte that matches the flag, it inserts an extra <strong>escape byte</strong> before it. This tells the receiver, “Hey, this byte is part of the data, not a frame boundary.” When the receiver sees the escape byte, it knows to treat the following byte as literal data, even if it looks like a flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*mTeIEHbBPEBoJ6Y5mWhJBA.png" /><figcaption>Mapping of bytes in byte stuffing. (picture by author)</figcaption></figure><h3>Error control</h3><p>As mentioned earlier, the data link layer provides <strong>unreliable delivery</strong> of packets from the upper layer. This is part of its defined interface — there’s no built-in guarantee of successful delivery, ordering, or even data integrity. So you might wonder: if the service is unreliable anyway, why bother detecting errors at all?</p><p>The answer lies in <strong>efficiency</strong>.</p><p>Even basic error detection at this level helps make better use of bandwidth. If corrupted data is caught early — right at the link layer — it can be discarded before wasting resources sending it further through the network stack. More importantly, if the protocol supports it, only the damaged frame needs to be resent, rather than allowing corrupted data to travel further up the stack. That way, higher layers like<strong> TCP</strong> don’t have to detect the problem and retransmit missing segments, which would otherwise consume more bandwidth and add delay.</p><p>To deal with corrupted frames, the data link layer relies on <strong>error-detecting</strong> and sometimes <strong>error-correcting</strong> codes. These are bits of information added to the frame that help the receiver decide whether the data was received correctly — or even fix it in some cases.</p><p><strong>Error-Detecting Codes</strong></p><p>At its core, error detection relies on a simple idea: you take the data in the frame, run it through a special function, and get a short result — usually just a number. This result is sent along with the data, typically at the end of the frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qi3KIifqhURQMsafUNZ9zQ.png" /><figcaption>Error code at the end of a frame. (picture by author)</figcaption></figure><p>When the frame arrives at the receiver, the same function is run on the received data. If the result matches the number sent with the frame, everything is probably fine. But if it doesn’t match, the receiver knows something went wrong — bits were lost or flipped — and the frame gets dropped.</p><p>This function behaves a bit like a <strong>hash function</strong>: small changes in the input produce very different outputs. But unlike typical hash functions used in cryptography, these error-checking functions are designed using math that makes them especially good at detecting the kinds of errors that happen on real transmission channels — like a burst of flipped bits or a single corrupted bit.</p><p><strong>Error-Correcting Codes</strong></p><p>Error correction takes things a step further. Instead of just detecting that something went wrong, the receiver can actually figure out what the original data was, even if some bits were corrupted during transmission.</p><p>The idea is similar: the sender runs a function on the original data, but instead of just producing a short check value, the result includes <strong>extra redundant information</strong> added into the frame itself. This redundancy is structured in a way that lets the receiver not only spot an error but also pinpoint where it happened and fix it — all without needing to ask the sender to resend anything.</p><p>These schemes are more complex and usually require more bandwidth, so they’re used where retransmission is difficult or expensive — like in satellite links, streaming media, or low-power wireless communication.</p><h3>Frame header</h3><p>So as you can see, we’ve been gradually building up the structure of a data link layer frame. We started with the raw data, then added frame boundaries to separate one chunk from another. After that, we introduced an error detection code at the end of the frame to help spot any corruption.</p><p>Now it’s time to add one more important part: the <strong>header</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l82kiwCgL6-HN-_cA1LZrA.png" /><figcaption>Header at the start of a frame. (picture by author)</figcaption></figure><p>The header sits at the beginning of the frame and carries <strong>metadata</strong> — small bits of information that help the protocol handle the frame properly. This can include things like:</p><ul><li>The <strong>size</strong> of the payload</li><li>The <strong>type</strong> of data being carried (to help the receiver know how to process it)</li><li><strong>Control flags</strong> used for flow control or acknowledgments</li><li><strong>Addressing information</strong>, to identify the sender or intended recipient</li><li>Any other <strong>protocol-specific instructions</strong> needed for the frame to be handled properly</li></ul><p>The exact contents of the header depend on the protocol in use, but the general idea is the same: the header gives the receiving side enough context to understand what this frame is, where it’s going, and how to treat it.</p><p>That’s it for now. In the next part, we’ll go a level deeper and build a simple custom data link protocol that supports <strong>connection-oriented, reliable transmission</strong>. We’ll take a closer look at how the header fields we just discussed can be used to manage things like sequencing, acknowledgments, and flow control. I’ll also walk through some of the most common real-world data link layer protocols in use today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a886860b993e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP/IP. Physical Layer]]></title>
            <link>https://medium.com/@mishastatnik/tcp-ip-physical-layer-f9c5b7149352?source=rss-efbd1fc5fbc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9c5b7149352</guid>
            <category><![CDATA[physical-layer]]></category>
            <category><![CDATA[wireless]]></category>
            <category><![CDATA[fiber]]></category>
            <category><![CDATA[bandwidth]]></category>
            <category><![CDATA[sattelite]]></category>
            <dc:creator><![CDATA[Miha_S]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 19:40:56 GMT</pubDate>
            <atom:updated>2025-06-12T20:11:43.272Z</atom:updated>
            <content:encoded><![CDATA[<p>So, the Physical Layer. This layer focuses on the methods of transmitting bits between devices that are directly connected. This transmission happens through various physical mediums. We will explore the following mediums: wires, optical fiber, radio waves, and communication satellites.</p><p>When discussing data transmission across any of these mediums, we refer to it as sending data via a <strong>communication channel</strong>. Each type of channel has inherent limitations on the amount of data that can be transmitted within a specific time frame. Maximizing this data transfer rate is a primary focus for protocol and algorithm developers working on the Physical Layer.</p><p>Each of these media has its own specific characteristics in terms of bandwidth, delay, cost, and ease of installation and maintenance.</p><p>These media are broadly classified into guided media (such as copper wires and fiber optics) and unguided media (including terrestrial wireless, satellite communication, and laser transmission through the air).</p><h3>Data rate theory</h3><p>What’s fascinating about transmission media is that they allow the simultaneous transmission of multiple digital signals. To fully grasp the details, you’d need some background in electronics, information theory, and Fourier transforms. But for now, I’ll keep it simple and demonstrate with a hands-on example.</p><p>In transmission media, signals are sent at different frequencies. For example, wires can transmit lower frequencies more easily, while higher frequencies tend to be attenuated. The range of frequencies that a medium can carry is called its <strong>bandwidth</strong>. Every transmission medium has a limited bandwidth, which constrains the maximum data rate that can be achieved. There’s a well-known theorem that tells us the theoretical maximum bitrate (in bits per second) that can be transmitted over a medium with a given bandwidth.</p><p>This theorem, known as the <strong>Shannon Capacity</strong> or Shannon-Hartley Theorem, states that the maximum achievable bitrate <em>C</em> over a communication channel with bandwidth <em>B</em> (in Hz) and a signal-to-noise ratio <em>SNR</em> is given by the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*Pc8pmd8Lcz9BeF0A" /></figure><p>This sets a theoretical limit on how fast we can transmit information without errors, regardless of how advanced our technology is.</p><p>The consequences are straightforward: the wider the bandwidth, the higher the potential bitrate. Similarly, the stronger the signal (resulting in a higher signal-to-noise ratio, or SNR), the greater the achievable bitrate.</p><p>The cool part is that we can actually divide a wire’s bandwidth into multiple sections, send separate signals within each section, and later filter and process these signals independently. This principle allowed early internet technologies to reuse existing telephone lines and cable TV infrastructure for data transmission. For example, telephone lines occupied the lower portion of the available spectrum on a wire, while internet signals were sent in the higher-frequency bands. By carefully separating these frequency ranges, both services could operate simultaneously on the same physical medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gR59zbvMqIJ3Erg57wNMZg.jpeg" /><figcaption>TV cables bandwidth division</figcaption></figure><h3>Wire transmission</h3><p><strong>Twisted pair<br></strong>One of the oldest and still most common transmission media. A twisted pair consists of two insulated copper wires, typically about 1 mm thick. The most common application of the twisted pair is the telephone system. Both telephone calls and ADSL Internet access run over these lines.</p><p><strong>Coaxial Cable</strong><br>The construction and shielding of the coaxial cable give it a good combination of high bandwidth and excellent noise immunity. Coax is still widely used for cable television and metropolitan area networks.</p><p><strong>Power Lines</strong><br>That may sound unusual, but you can actually transmit data over power lines. As you can remember, previously it was described how you can divide bandwidth of a cable for different signals, the same can be done for power lines. The actual power is transmitter at lower frequency spectrum, while the higher can be used for signals. <br>It proved to be unusable for high frequency applications of networks, but there exist cases, where power lines were used for transmitting data.</p><p><strong>Fiber Optics<br></strong>And the coolest of all — Fiber Optics. It’s the newest and fastest method for transmitting information today. Instead of electrical signals, fiber optics use pulses of light to carry data through thin strands of glass or plastic fibers. This works because the light signals reflect internally within the fiber in a process called total internal reflection, allowing the data to travel long distances with very little loss or interference. Thanks to this technology, fiber optic cables can deliver incredibly high speeds and large bandwidths.</p><h3>Wireless transmission</h3><p>There’s something called the <strong>electromagnetic spectrum</strong>. Basically, it’s made up of invisible waves called electromagnetic waves that travel through space. One important property of these waves is their frequency, which tells us how many wave cycles pass by per second.</p><p>When we consider all possible frequencies of these waves, we get the entire electromagnetic spectrum. Here’s what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBxtsqd3MHRX0LuMZ1c2_A.jpeg" /><figcaption>Electromagnetic spectrum</figcaption></figure><p>We will focus on the <strong>Radio</strong>, <strong>Microwave</strong>, and <strong>Infrared</strong> parts of the electromagnetic spectrum. The general principles that apply to these frequencies are:<br>1. They follow the equation we discussed earlier: the wider the frequency<strong> </strong>spectrum, the higher the potential data rates.<br>2. The <strong>lower the frequency</strong>, the better the waves can <strong>penetrate buildings and other obstacles</strong>, and the more they tend to be <strong>omnidirectional</strong> — meaning they spread out in all directions. However, lower-frequency signals also lose power more quickly over distance because their energy spreads thinly over a larger area.</p><p><strong>Politics<br></strong>To prevent total chaos there are national and international agreements about who gets to use which frequencies. Since everyone want higher data rate everyone wants more spectrum. Thus national governments allocate spectrum for AM and FM radio, television, and mobile phones, as well as for telephone companies, police, maritime, navigation, military, government, and many other competing users.</p><p>And even when some piece of spectrum is allocated for some use, such as mobile phones, there is a decision to be made which company gets which part of that spectrum. This is usually done by auction off bandwidth to the highest bidder.</p><p>Also most governments have set aside some frequency bands called the ISM (Industrial, Scientific, Medical) bands for unlicensed usage. Garage door openers, cordless phones, radio-controlled toys, wireless mice, and numerous other wireless household devices use ISM bands.</p><p><strong>Radio Transmission<br></strong>Radio frequency waves are easy to generate, can travel long distances, and can penetrate buildings easily. Radio waves are also omnidirectional, meaning that they travel in all directions from the source, so the transmitter and receiver do not have to be carefully aligned physically.<br>At high frequencies radio waves tend to travel in straight lines and bounce off obstacles. High-frequency radio waves are also absorbed by rain and other obstacles.</p><p>Because radio waves travel omnidirectionally — spreading out in all directions — <strong>interference</strong> is a major challenge in this domain. Interference happens when two different transmitters send signals on the same frequency, causing their signals to overlap and disrupt each other. To manage this, governments strictly regulate the use of radio frequencies. In other words, the radio frequency spectrum is <strong>not open for unrestricted use</strong>; you must obtain special permission or a license from authorities to legally transmit on specific frequencies with your devices.</p><p><strong>Microwave Transmission</strong><br>Above 100 MHz the waves travel in nearly straight lines and can therefore be narrowly focused. This directionality allows multiple transmitters lined up i a row to communicate with multiple receivers in a row without interference. Microwave do not pass through walls and at frequencies above 4 GHz they are absorbed by water — therefore absorbed by rain.</p><p><strong>Infrared Transmission<br></strong>Unguided infrared waves are widely used for short-range communication. Like remove controls to TV, VCRs and stereos. They do not pass through solid object so no license is required for them.</p><p><strong>Light transmission</strong><br>You can actually communicate using <strong>laser beams</strong> by setting up a laser transmitter at one end and a receiver at the other, passing pulses of light to transmit data. However, there are significant challenges with this method. First, the laser beam is very narrowly focused, so even small disturbances — like wind or temperature changes — can distort or misalign the beam, disrupting communication. Additionally, laser beams cannot penetrate through rain, fog, or other obstacles, which limits their reliability in many environments.</p><h3>Communication Satellites</h3><p>In its simplest form a communication satellite can be thought as a big microwave repeater in the sky. It contains several transponders, each of which listens to some portion of the spectrum, amplifies the incoming signal, and then rebroadcasts it to another frequency to avoid interference with the incoming signal. This mode of operation is known as bent pipe.</p><p>The higher the satellite is the longer its orbiting period around the earth. So low-orbit satellites pass out of view fairly quickly, so many of them are needed to provide continuous coverage and ground antennas must truck them. At an altitude of about 35,800 km, the period is 24 hours.</p><p><strong>Geostationary satellites</strong><br>These are satellites that are places at 35,800 km high, so they appear to remain motionless in the sky , so they are not needed to be tracked. They are also called GEO (Geostationary Earth Orbit) satellites. There can be only 180 of such satellites to avoid interference, so a lot of countries claim their right to get them one of places in this orbit. They also have quite big propagation delay, around 270 ms.</p><p><strong>Low-Earth Orbit Satellites</strong><br>They move rapidly around the Earth at altitudes between about 500 to 2,000 kilometers. Because they cover only a small area at any given time and move quickly, you need a <strong>large constellation</strong> of these satellites working together to provide continuous global coverage. One successful example of such a system is the <strong>Iridium satellite network</strong>. Iridium consists of dozens of LEO satellites that communicate with each other and with ground stations to provide reliable voice and data services anywhere on the planet — even in the most remote areas.</p><p>The modern version of such satellite systems is the famous Elon Musk’s Starlink constellation.</p><p>Unlike GEO, instead of just bouncing signals back and forth, LEO satellites have onboard processing and routing capabilities. They can communicate directly with each other in space through laser links, creating a dynamic, mesh-like network. This allows data to be routed efficiently across the satellite constellation before reaching the ground, reducing latency and increasing speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LorQhZ4qz-0USbGqGvbV-w.jpeg" /><figcaption>Satellites guiding a data from one point to another.</figcaption></figure><h3>Wrapping up</h3><p>That’s it for the Physical Layer! I hope you’ve gained some new and interesting insights — because I definitely did while exploring this topic. In the next chapter, we’ll dive into a layer that we can explore more deeply: the <strong>Data Link Layer</strong>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c5b7149352" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP/IP. Intro]]></title>
            <link>https://medium.com/@mishastatnik/tcp-ip-intro-12912282770e?source=rss-efbd1fc5fbc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/12912282770e</guid>
            <category><![CDATA[network-protocols]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[ip]]></category>
            <dc:creator><![CDATA[Miha_S]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 16:25:58 GMT</pubDate>
            <atom:updated>2025-04-11T16:25:58.763Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first article in a series exploring the TCP/IP protocol stack from the bottom up. The series will focus only on the essential principles of TCP/IP that a programmer needs in order to understand how modern networking works.</p><p>I’m not an expert in this domain — in fact, I’m still learning it myself. A lot of the information in this series will be based on the book <em>Computer Networks</em> by Tanenbaum and Wetherall. But I believe that’s exactly why I can highlight the important details, especially those that weren’t immediately clear to me. Hopefully, this will help others like me who are going through the same learning journey.</p><p>So without further ado, let’s start with an overview of the TCP/IP model.</p><h3>Model</h3><p>We can describe the TCP/IP model in terms of different layers, ordered from bottom to top.<br> In the context of a networking model, a <strong>layer</strong> usually means the following:<br>A layer is a set of protocols that implement a specific interface defined for that layer. Typically, a layer provides an interface to the layer above it and uses the interface implemented by the layer below. These interfaces vary between layers, and we’ll look at each one in more detail when we study them individually.<br>A <strong>protocol</strong>, in turn, is simply a set of rules that define how two parties (such as two servers, or a phone and a router) can communicate with each other.</p><blockquote>An artificial protocol example consisting of 3 rules.<br>1. I send you a message. <br>2. If you receive the message, you reply with: “<strong>received</strong>”.<br>3. If I don’t get your “<strong>received</strong>” reply within 10 seconds, I assume something went wrong and resend the message.</blockquote><p>This layered approach is convenient because each layer depends only on the interface provided to it — not on the specific implementation. That means multiple protocols can implement the same interface. It’s similar to how an interface works in a programming language: different classes can implement the same interface in different ways. In networking, the “interface” isn’t a code structure, but rather a defined set of functionalities that a protocol must provide.</p><p>Here are the layers of the TCP/IP model that we’ll be considering in this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*KDmDbblDbTrU95az9wg6bQ.png" /><figcaption>TCP/IP layers</figcaption></figure><blockquote>In the official definition of the TCP/IP model, the physical layer isn’t included — but we’ll include it here to present a more complete and practical picture.</blockquote><h3>Physical Layer</h3><p>The <strong>physical</strong> layer is concerned with how to transmit bits between devices over different types of media. This includes transmission over wires, radio waves, light (like in fiber optics), and more.<br>It’s important to understand that this layer does <strong>not</strong> guarantee that a message will be correct at the receiver — or even that it will be delivered at all. It does not indicate start and end of message, it just sends a stream of bits. Ensuring correctness and delivery is the responsibility of the upper layers.<br>Also, the physical layer typically only deals with communication between <strong>two directly connected devices:</strong> your laptop and a Wi-Fi router, a phone and a 4G tower, two phones communicating via Bluetooth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*4rF5bW9oHiAo_C6mHQWwpg.png" /><figcaption>Transmitting bits via radio waves between laptop and router</figcaption></figure><h3>Link Layer</h3><p>The <strong>link</strong> layer is responsible for sending finite-length messages — often called <strong>packets</strong> — between <strong>directly connected devices </strong>(<em>still only between two devices, this layer does not know how to connect to other devices on the network</em>), with a specified level of reliability. Yes, you read that right: we don’t require that a packet is always delivered correctly, just that it is delivered correctly with a <strong>high enough</strong> <strong>probability</strong>. The reality is, you can never be 100% sure a packet was received without errors — you can only estimate it with a very high degree of confidence. However, in practice, this probability is made so high (using things like error-detecting and error-correcting codes) that we can usually <em>assume</em> packets are delivered correctly. For most practical purposes, it’s close enough to certainty.<br>The concept of <em>finite-length messages</em> means that we can’t send large files or data streams over the network all at once. Instead, we divide them into smaller chunks — called <strong>packets</strong>. These packets are sent individually over the network and then reassembled on the receiving side to reconstruct the complete file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*hSScONCFA7PCU5Alw7iNYw.png" /><figcaption>Dividing file into packets and sending it to other device via link layer</figcaption></figure><h3>Network Layer</h3><p>The <strong>network</strong> layer is, in many ways, the most fundamental layer for understanding networking (<em>no pun intended</em>). It’s responsible for figuring out how to combine multiple links into <strong>networks</strong>, and then connect those networks into <strong>inter-networks</strong> — so that we can send packets between distant devices, even if they’re not directly connected.</p><p>You can think of the Internet (the massive network that spans the entire globe) as a collection of devices, some of which have <strong>direct connections</strong> to each other. The job of the network layer is to find a path from <strong>Device A</strong> to <strong>Device B</strong>, even if they’re not connected directly. Instead, it uses a series of <strong>intermediate devices</strong> and connections to get the packet where it needs to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*y-Yn_O5EY7NaglPyx1m_3A.png" /><figcaption>Finding a path for a packet in a network</figcaption></figure><p>But just like the physical layer, the <strong>network layer is not responsible for the correctness of delivery</strong>. It does not guarantee that a packet will actually reach its destination.<br>It also doesn’t detect if a packet has been <strong>delivered more than once</strong> — which can happen, for example, if the same packet takes multiple paths through the network. Nor does it <strong>preserve the order of packets</strong>; they might arrive out of sequence depending on the route each one takes.<br>And that’s exactly why we need the <strong>next layer</strong> — the <strong>transport layer</strong> — which adds these critical features to ensure reliable and orderly communication between applications.</p><h3>Transport Layer</h3><p>There are two widely known protocols at this layer: <strong>TCP</strong> and <strong>UDP</strong>, both implemented at the operating system level. The common factor between them is that both add the concept of ports to network packets. These ports essentially tell the operating system which application on the device should receive the packet.</p><p>Applications that use the UDP protocol must handle the delivery of packets themselves, as UDP does <strong>not guarantee reliable delivery</strong> (it is essentially a network protocol with a port number). In some cases, applications may prioritize speed over reliability, opting to send data quickly, even if it could be corrupted. This is why UDP is commonly used for real-time applications such as live video or voice transmissions.</p><p>On the other hand, TCP (Transmission Control Protocol) ensures the <strong>reliable delivery of data</strong>. It establishes a connection between the sender and receiver before transmitting data, meaning the devices exchange information to initiate the communication and ensure proper packet delivery. TCP guarantees that packets arrive in order and without errors. For developers, TCP is represented as a <strong>reliable</strong> stream of bytes of data (often referred to as sockets) that can be sent or received between the parties.</p><h3>Application Layer</h3><p>The application layer is the most familiar to us as programmers. There are countless protocols implemented at this level, with some of the most widely used being HTTP, DNS, the email protocol SMTP, FTP for file transfers, and SSH for secure remote access. These protocols rely on transport layer protocols like TCP and UDP to function, and they provide a more convenient, high-level interface for developers to build networked applications without dealing with the complexities of the lower layers.</p><h3>Wrapping Up</h3><p>I hope this article provided a general understanding of modern networking architecture. In the upcoming articles, I’ll dive deeper into each of these layers, exploring their roles, protocols, and how they interact. The image below gives an overview of the level of detail you can expect for each layer — darker backgrounds indicate more in-depth and thorough explanations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Olf-fE34vaPsJUv6bqsOlQ.png" /><figcaption>Level of explanations for each layer</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12912282770e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>