Networking Basics - Learn With Examples https://learnwithexamples.org/category/computer-science-concepts/networking-basics/ Lets Learn things the Easy Way Tue, 13 Oct 2026 14:12:25 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.3 https://i0.wp.com/learnwithexamples.org/wp-content/uploads/2026/07/cropped-learnwithexamples-icon.png?fit=32%2C32&ssl=1 Networking Basics - Learn With Examples https://learnwithexamples.org/category/computer-science-concepts/networking-basics/ 32 32 228207193 Top 20 Networking Interview Questions with Plain-English Answers https://learnwithexamples.org/top-20-networking-interview-questions/ https://learnwithexamples.org/top-20-networking-interview-questions/#respond Tue, 13 Oct 2026 14:12:21 +0000 https://learnwithexamples.org/?p=973 I have sat on both sides of the interview table for a long time, and I can tell you something that surprises most candidates: interviewers rarely want a textbook definition.…

The post Top 20 Networking Interview Questions with Plain-English Answers appeared first on Learn With Examples.

]]>

I have sat on both sides of the interview table for a long time, and I can tell you something that surprises most candidates: interviewers rarely want a textbook definition. They want to hear whether you actually understand what happens when two computers talk. This guide gives you the twenty questions that come up again and again, each answered the way you would say it out loud, with a real-world picture, a “what the interviewer wants to hear” note, and a few small programs whose output I ran so the numbers are real.

How to use this guide

Read the questions in order the first time, because later answers lean on earlier ones. Subnets make more sense after IP addresses, and the “what happens when you type a URL” question ties together half the list. After that, use the headings to jump to whatever you are weakest on.

The one rule for answering. Give the one-sentence definition first, then a quick real-world picture, then one detail that proves you have actually used it. Three short layers beat a long speech. If the interviewer wants more, they will ask, and that is when the conversation gets good.

Questions 1 to 5 cover the foundations. Questions 6 to 11 cover the protocols that make the internet work. Questions 12 to 15 cover devices and routing, and 16 to 20 cover security and troubleshooting.

Part 1: The foundations

Q1 What is a computer network, and what are LAN, WAN and MAN?

The interviewer wants to hear: that a network is just devices sharing data, and that the types differ by reach.

A network is two or more devices connected so they can exchange data. Everything else is about scale. A LAN (local area network) covers a small area such as a home, an office floor or a school lab. A MAN (metropolitan area network) spans a city or a campus. A WAN (wide area network) links networks across cities or countries, and the internet is the largest WAN there is.

Real-world picture: your home Wi-Fi is a LAN. The company that runs your office has LANs in Delhi and Pune joined by a leased line, and that link is a WAN.

Q2 Explain the OSI model and the TCP/IP model.

The interviewer wants to hear: that layers split a big problem into small ones, and that you can name what happens at each.

The OSI model is a seven-layer teaching framework for how data travels. Each layer does one job and talks only to the layers directly above and below it. The TCP/IP model is the four-layer version the real internet is built on. Interviewers love asking for both because the layers give you a map for troubleshooting.

OSI model (7 layers)TCP/IP model (4 layers)7 ApplicationHTTP, DNS, SMTP6 PresentationEncryption, encoding5 SessionSessions, dialogue4 TransportTCP, UDP, ports3 NetworkIP, routing2 Data LinkMAC, switches1 PhysicalCables, radio, bitsApplicationDataTransportSegment / datagramInternetPacketLinkFrame / bitsMnemonic from the top: All People Seem To Need Data Processing
OSI has seven layers, TCP/IP has four. The data unit gets a new name at each stage.

A handy memory trick for the OSI layers from the top is: All People Seem To Need Data Processing (Application, Presentation, Session, Transport, Network, Data Link, Physical). In practice, people use the layer numbers as shorthand. When an engineer says “layer 2 problem,” they mean something about switches and MAC addresses. “Layer 3” means IP and routing, and “layer 4” means TCP or UDP ports.

Real-world picture: posting a parcel. You write the letter (application), put it in an envelope with an address (network), a courier packs it into a truck (data link), and the truck drives on the road (physical). Each stage ignores how the others do their work.

Q3 What is an IP address? What is the difference between IPv4 and IPv6, and between public and private?

The interviewer wants to hear: 32 versus 128 bits, and why private ranges exist.

An IP address is the logical address of a device on a network, used to route data to it. IPv4 addresses are 32 bits long, written as four numbers such as 192.168.1.10, giving about 4.29 billion possible addresses (232 is exactly 4,294,967,296). That turned out not to be enough for a world of phones and sensors. IPv6 addresses are 128 bits, which gives roughly 3.4 × 1038 addresses, an almost unimaginable number.

Private addresses are reserved for use inside networks and are not routed on the public internet. The three ranges are 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Public addresses are unique across the internet. Because many homes reuse the same private ranges, NAT (Question 13) lets them all share one public address.

Real-world picture: private addresses are like room numbers inside a hotel. Room 204 exists in thousands of hotels, but it only means something inside one building. The hotel’s street address is the public one.

Q4 What is a subnet mask and what is subnetting?

The interviewer wants to hear: that a mask splits an address into network and host parts, and that you can do the arithmetic.

A subnet mask tells a device which part of an IP address identifies the network and which part identifies the host. The mask 255.255.255.0 means the first three numbers name the network and the last one names the device. Engineers also write it as CIDR notation: 192.168.10.0/24, where 24 is the count of network bits.

Subnetting means cutting one large network into smaller ones, usually for tidiness, security or to reduce broadcast traffic. The useful formula: a network with a prefix length of n has 2(32 − n) addresses, and two of those are reserved (the network address and the broadcast address), so the usable host count is 2(32 − n) − 2. A /24 gives 254 hosts. A /26 gives 62.

Here is a short Python program that does the arithmetic with the standard ipaddress module. It splits a /24 into four /26 subnets.

import ipaddress

net = ipaddress.ip_network("192.168.10.0/24")
print(net, "has", net.num_addresses, "addresses,", net.num_addresses - 2, "usable hosts")
print("mask:", net.netmask)
print()
print("Split into four /26 subnets:")
for s in net.subnets(new_prefix=26):
    hosts = list(s.hosts())
    print(f"{str(s):<18} hosts {hosts[0]} - {hosts[-1]}   broadcast {s.broadcast_address}")

Output:

192.168.10.0/24 has 256 addresses, 254 usable hosts
mask: 255.255.255.0

Split into four /26 subnets:
192.168.10.0/26    hosts 192.168.10.1 - 192.168.10.62   broadcast 192.168.10.63
192.168.10.64/26   hosts 192.168.10.65 - 192.168.10.126   broadcast 192.168.10.127
192.168.10.128/26  hosts 192.168.10.129 - 192.168.10.190   broadcast 192.168.10.191
192.168.10.192/26  hosts 192.168.10.193 - 192.168.10.254   broadcast 192.168.10.255

Read each line as a mini network: the first usable host, the last usable host, and the broadcast address at the end. Interviewers who ask this question often give you a block like 192.168.10.0/24 and ask you to carve out four equal subnets. The answer is the table above, and the trick is that each /26 holds 64 addresses, so the blocks start at 0, 64, 128 and 192.

Q5 What is the difference between a MAC address and an IP address?

The interviewer wants to hear: local identity versus logical location.

A MAC address is a 48-bit hardware identifier burned into a network card, written like 3C:52:82:AB:12:EF. It is used for delivery within one local network. An IP address is assigned by software or a DHCP server, can change, and is used to route data between networks.

Real-world picture: your name is your MAC address, and it goes wherever you go. Your postal address is your IP address, and it changes when you move house. The post office sorts by postal address across the country, but the final handover at your door is to you by name.

One more detail worth saying: as a packet crosses several routers, the IP addresses at both ends stay the same, but the MAC addresses are rewritten at every hop. That single sentence tells an interviewer you understand how layers 2 and 3 cooperate.

Part 2: The protocols that run the internet

Q6 What is the difference between TCP and UDP?

The interviewer wants to hear: reliability versus speed, with an example of each.

TCP is connection-oriented. It sets up a connection first, numbers the data, retransmits what is lost and delivers it in order. UDP is connectionless. It just sends packets with no handshake, no retransmission and no ordering guarantee, so it is faster and lighter.

FeatureTCPUDP
ConnectionHandshake firstNone
DeliveryGuaranteed and orderedBest effort
SpeedSlower, more overheadFaster, less overhead
Used forWeb pages, email, file transfer, SSHDNS lookups, voice and video calls, games, streaming
Real-world picture: TCP is registered post with a signature at the end. UDP is a postcard. In a live video call, a lost frame is not worth resending because the moment has already passed, so a postcard is the right choice.

Q7 Explain the TCP three-way handshake.

The interviewer wants to hear: SYN, SYN-ACK, ACK, and why it exists.

Before TCP sends any data, the two sides agree to talk. The client sends a SYN (“I want to connect, my starting sequence number is X”). The server answers with SYN-ACK (“Got it, here is mine, Y”). The client finishes with an ACK (“Got yours too”). Now both sides know the other is alive and reachable, and they have agreed on sequence numbers for tracking data.

CLIENTSERVER1 SYNI want to connect, my sequence is x2 SYN-ACKOK, mine is y, I expect x+13 ACKGot it, I expect y+1Connection established. Data can now flow both ways.
Three messages open a TCP connection. Closing normally takes FIN and ACK messages in each direction.
Real-world picture: a phone call. “Hello, can you hear me?” “Yes, can you hear me?” “Yes. Okay, let us talk.”

A bonus line that impresses: a SYN flood attack sends huge numbers of SYNs and never completes the handshake, leaving the server holding half-open connections. Defences include SYN cookies and rate limits.

Q8 What is DNS and how does a lookup work?

The interviewer wants to hear: the hierarchy and that caching is why it is fast.

DNS, the Domain Name System, is the internet’s phone book. People remember names like example.com, but computers need IP addresses, and DNS translates one into the other.

When your device needs an address, it asks a recursive resolver, usually run by your ISP or a public DNS service. If the resolver does not already have the answer cached, it asks a root server, which points it to the server for the top-level domain (.com, .org, .in). That server points to the domain’s authoritative server, which gives the real answer. The resolver returns it to you and remembers it for the record’s time to live (TTL).

Your devicebrowserResolvercaches answersRoot serverpoints to .comTLD server (.com)points to the domainAuthoritativeknows the real IP12345. The resolver sends the IP address back to you and remembers it until the TTL expires.
A DNS lookup follows a chain from resolver to root to TLD to authoritative server, and every answer is cached.

Know the common record types: A (name to IPv4), AAAA (name to IPv6), CNAME (an alias to another name), MX (mail servers) and NS (which servers are authoritative). Plain DNS uses UDP port 53, and TCP port 53 is used for large responses.

Q9 What is DHCP and how does it work?

The interviewer wants to hear: automatic address assignment and the four-step DORA exchange.

DHCP, the Dynamic Host Configuration Protocol, automatically gives a device an IP address, subnet mask, default gateway and DNS servers when it joins a network. The exchange is nicknamed DORA: the client broadcasts a Discover, the server sends an Offer, the client sends a Request for that offer, and the server sends an Acknowledge. The address is a lease, not a permanent grant, and the client renews it before it expires.

Real-world picture: the front desk at a hotel handing you a room key that works until checkout. If you see an address beginning with 169.254 on your laptop, it means no DHCP server answered and the device gave itself a fallback address.

Q10 What is ARP and why is it needed?

The interviewer wants to hear: that ARP maps an IP address to a MAC address on the local network.

On a local network, devices deliver frames by MAC address, but programs only know IP addresses. ARP, the Address Resolution Protocol, bridges the gap. When your PC wants to reach 192.168.1.1 and does not know its MAC, it broadcasts “Who has 192.168.1.1?” to everyone. The owner replies with its MAC address. Your PC stores the answer in its ARP cache for a while, so it does not need to ask again.

The classic security follow-up is ARP spoofing: an attacker sends false ARP replies so that traffic meant for the gateway flows through their machine. Managed switches can defend against it with features such as dynamic ARP inspection.

Q11 What happens when you type a URL into your browser and press Enter?

The interviewer wants to hear: an ordered story that touches DNS, TCP, TLS and HTTP. This is the most famous question on the list, and it is really a test of the previous ten.

Here is the version I recommend you tell, in order:

  • 1. The browser checks its caches and the operating system’s cache for a known address.
  • 2. DNS lookup. If nothing is cached, it resolves the name to an IP address (Question 8).
  • 3. TCP connection. The browser opens a connection to port 443 with the three-way handshake (Question 7).
  • 4. TLS handshake. For HTTPS, both sides agree on encryption and the server proves its identity with a certificate.
  • 5. HTTP request. The browser sends GET / with headers.
  • 6. The server responds with a status code (200 for success) and the page.
  • 7. The browser renders the page, requesting images, scripts and styles, often over the same connection.

Mention that on your local network, the first packet needs ARP to find the gateway’s MAC address, and that routers along the way forward the packet by IP. That shows you can connect every layer in one story.

Part 3: Devices and routing

Q12 What is the difference between a hub, a switch and a router?

The interviewer wants to hear: three devices, three layers, three levels of intelligence.
DeviceWorks atHow it forwardsIntelligence
HubLayer 1Repeats every signal out of every portNone, and now rare
SwitchLayer 2Learns MAC addresses and sends frames only to the right portMedium
RouterLayer 3Looks at IP addresses and connects different networksHigh
Real-world picture: a hub is someone shouting a message to the entire room. A switch is a receptionist who knows where each person sits and walks the note to the right desk. A router is the post office that sends mail between towns.

Q13 What is NAT?

The interviewer wants to hear: private to public translation, and that ports make it work.

NAT, Network Address Translation, lets many devices with private addresses share one public IP address. The router rewrites the source address and port of outgoing packets and keeps a table. When replies come back, it looks up the table and forwards them to the right internal device. The common form, where ports tell the devices apart, is often called PAT or NAT overload.

Know the side effects. NAT helped the world survive IPv4 exhaustion, and it hides internal addresses from the outside. But it is not a firewall, and it breaks anything that needs inbound connections, which is why we use port forwarding to reach a server inside a home network.

Q14 What is a default gateway, and how does a router choose where to send a packet?

The interviewer wants to hear: the routing table and the longest-prefix-match rule.

A default gateway is the router a device uses for any destination outside its own subnet. Your laptop does not know how to reach the whole internet, so it hands everything non-local to the gateway.

A router keeps a routing table, a list of destination networks and where to send traffic for each. When a packet arrives, the router finds every entry that matches the destination and picks the most specific one, meaning the longest prefix. That is the longest prefix match. The entry 0.0.0.0/0 is the default route and matches everything, but because it is the least specific, it only wins when nothing better matches.

Here is a tiny router in Python with four routes:

import ipaddress

routes = {
    "0.0.0.0/0":   "ISP (default route)",
    "10.0.0.0/8":  "Head office core",
    "10.1.0.0/16": "Branch office",
    "10.1.2.0/24": "Branch lab network",
}

def lookup(dest):
    ip = ipaddress.ip_address(dest)
    best = None
    for prefix, hop in routes.items():
        net = ipaddress.ip_network(prefix)
        if ip in net and (best is None or net.prefixlen > best[0].prefixlen):
            best = (net, hop)
    return best

for dest in ["10.1.2.50", "10.1.9.9", "10.7.7.7", "8.8.8.8"]:
    net, hop = lookup(dest)
    print(f"{dest:<10} matches {str(net):<12} -> {hop}")

Output:

10.1.2.50  matches 10.1.2.0/24  -> Branch lab network
10.1.9.9   matches 10.1.0.0/16  -> Branch office
10.7.7.7   matches 10.0.0.0/8   -> Head office core
8.8.8.8    matches 0.0.0.0/0    -> ISP (default route)

Look at the first line. The address 10.1.2.50 matches the /8, the /16 and the /24, and the /24 wins because it is the most specific. The last line matches only the default route, which sends it to the ISP.

One more thing interviewers like: routes can be static (written by an administrator) or dynamic (learned from other routers using protocols such as OSPF inside an organisation and BGP between internet providers). Static is simple and predictable. Dynamic adapts when links fail.

Q15 What is a VLAN and why would you use one?

The interviewer wants to hear: logical separation on shared hardware.

A VLAN, virtual LAN, splits one physical switch into several logical networks. Devices in different VLANs cannot talk directly even if they are plugged into the same switch, and they need a router (or a layer 3 switch) to communicate. Frames carry a VLAN tag following the 802.1Q standard when they travel between switches.

The reasons to use them are security (keep guest Wi-Fi away from the finance team), performance (smaller broadcast domains) and tidiness (group devices by function, not by cable location).

Real-world picture: one office building with separate locked floors for different companies. Everyone shares the same lifts and walls, but you cannot walk into another company’s space without going through reception.

Part 4: Security and troubleshooting

Q16 What is a firewall?

The interviewer wants to hear: rules on traffic, and the stateless versus stateful difference.

A firewall filters network traffic by rules, allowing or blocking it based on things like source, destination, port and protocol. A stateless firewall checks each packet alone against the rules. A stateful firewall tracks connections, so it knows that an incoming packet is a reply to something you started, and it allows it automatically. Modern “next-generation” firewalls also look at applications and can detect certain threats.

The principle to quote is default deny: block everything, then allow only what you need. That way, a mistake leaves you too closed instead of too open.

Q17 What is the difference between HTTP and HTTPS?

The interviewer wants to hear: encryption, certificates and ports 80 and 443.

HTTP sends web traffic in plain text on port 80, so anyone on the path can read or alter it. HTTPS is the same protocol carried inside TLS encryption, usually on port 443. TLS gives you three things: confidentiality (nobody can read it), integrity (nobody can change it unnoticed) and authentication (a certificate proves you reached the real site).

If asked how the handshake works, a safe outline is: the client says hello and lists its supported options, the server answers with its certificate, the client checks the certificate against trusted authorities, and both sides agree on session keys, which then encrypt the data. Modern TLS also uses temporary keys, so recorded traffic stays unreadable even if a server key leaks later.

Q18 What is a VPN, and how is it different from a proxy?

The interviewer wants to hear: tunnel versus middleman.

A VPN creates an encrypted tunnel between your device and a VPN server, and typically sends all your traffic through it. Companies use VPNs so remote staff can reach internal systems as if they were in the office. A proxy is a server that makes requests on your behalf, usually for particular applications, and it may not encrypt anything. A VPN protects the whole path to the VPN server. A proxy mainly changes where the request appears to come from or adds filtering and caching.

Be careful with claims. A VPN hides your traffic from the local network and your ISP, but the VPN provider can see it instead. It does not make you anonymous.

Q19 How do you troubleshoot “the internet is not working”? What do ping and traceroute do?

The interviewer wants to hear: a method, not guesses. Work from near to far.

Ping sends a small ICMP echo request and waits for a reply. It tells you whether a host is reachable and how long the round trip takes. Traceroute (called tracert on Windows) lists the routers on the path by sending packets with increasing TTL values, so each router in turn reports back when the TTL runs out. It shows you where along the path things slow down or stop.

My own habit is a four-step ladder, working outward until something fails:

1 Ping 127.0.0.1your own network stackFails: this machine2 Ping gatewaye.g. 192.168.1.1Fails: cable, Wi-Fi, gateway3 Ping 8.8.8.8a public IPFails: ISP or beyond4 Ping a namee.g. example.comFails: DNSWork outward. The first step that fails shows where to look.
Test close to home first. The first step that fails tells you which layer to investigate.
  • Ping 127.0.0.1. If this fails, the network software on your own machine is broken.
  • Ping the default gateway. If this fails, the problem is local: cable, Wi-Fi, switch or gateway.
  • Ping a public IP such as 8.8.8.8. If this works but names fail, you are nearly at DNS. If it fails, the problem is beyond the gateway, maybe the ISP.
  • Ping a domain name. If the IP works but the name does not, DNS is the culprit.

Also check the basics early: is the address a 169.254 one (DHCP failed), is the cable plugged in, and did anything change recently? In my experience, most “mysterious” outages are one of those three.

Q20 What is the difference between bandwidth, latency and throughput?

The interviewer wants to hear: that fast internet is not one number.

Bandwidth is the maximum amount of data a link can carry per second, like the number of lanes on a highway. Latency is how long a single piece of data takes to get there, like the time for one car to complete the trip. Throughput is the amount that actually gets through in practice, which is usually lower than bandwidth because of congestion, errors and protocol overhead.

Real-world picture: a satellite link can have huge bandwidth, a wide highway, but high latency, a very long road. Downloading a big file is fine. A fast-paced online game feels terrible, because every action waits for a long round trip.

It is worth adding that a bigger plan does not fix a latency problem. When someone says “my connection is fast but pages feel slow,” look at latency, DNS and packet loss before blaming bandwidth.

How the same question changes by role

The twenty questions above are common, but interviewers adjust the depth to the job. Click a tab to see what each role is really probing for.

Help desk or IT support

You are the first person someone calls when their laptop cannot reach anything.

FocusTroubleshooting
CoreIP, DHCP, DNS
Toolsping, ipconfig
StyleStep by step

What they probe. Expect Questions 3, 9, 10 and 19 in some form. They want a calm method: check the cable or Wi-Fi, look for a 169.254 address, ping the gateway, then a public IP, then a name. Say each step out loud and what a failure at that step would mean.

Network engineer

You design and maintain the switches, routers and links that a company depends on.

FocusDesign and routing
CoreVLANs, OSPF, BGP
MathsSubnetting
ToolsCLI, Wireshark

What they probe. Expect deep dives into Questions 4, 12, 14 and 15: carve a block into subnets on a whiteboard, explain how a routing table picks a path, how a VLAN trunk works, and what happens when a link fails. Quote real protocols and mention labs you have built.

Backend developer

You write services that talk to databases, APIs and browsers across a network.

FocusHow apps use it
CoreHTTP, TCP, DNS
SkillsTimeouts, TLS
QuestionQ11 favourite

What they probe. The URL question (Q11) is almost guaranteed. Be ready for follow-ups on TCP versus UDP, what a timeout or a connection reset means, how DNS caching can cause stale answers after a deploy, and how HTTPS certificates fail. Latency and connection reuse come up often.

DevOps or cloud

You build and run infrastructure in a cloud, where networks are made from settings, not cables.

FocusCloud networks
CoreCIDR, NAT, LB
IdeasVPC, subnets
ToolsCloud console

What they probe. Subnetting and CIDR (Q4) matter a lot, because you will plan address ranges for virtual private clouds. Expect NAT (Q13), firewalls and security groups (Q16), DNS records (Q8), and a scenario such as why a private server cannot reach the internet. The answer often involves a missing route or NAT gateway.

Security analyst

You watch traffic for things that should not be there and harden what is exposed.

FocusAttack and defence
CoreFirewalls, TLS
KnowARP spoofing
MindsetDefault deny

What they probe. Expect Questions 7, 10, 16, 17 and 18 with an attacker’s twist: SYN floods, ARP spoofing, why HTTP is unsafe, what a VPN does and does not hide, and how stateful firewalls track connections. Strong answers always state both the attack and the defence.

Common mistakes candidates make

  • Reciting definitions with no example. A definition shows memory. An example shows understanding.
  • Mixing up layers. Saying a switch “routes” or that IP is at layer 2 is the quickest way to lose credibility.
  • Confusing the port with the protocol. Port 443 is conventionally HTTPS, but a program can use any port.
  • Forgetting that DNS uses UDP. Most do not mention that TCP is used for large answers and zone transfers.
  • Claiming NAT is a firewall. It hides addresses as a side effect. It does not enforce a security policy.
  • Guessing in troubleshooting questions. Describe your method out loud. Interviewers care more about how you think than what you land on.
  • Bluffing. “I have not used that, but here is how I would find out” works far better than inventing an answer.

A study plan that actually works

If you have two weeks, here is the order I recommend. Spend the first few days on layers, IP, subnets and TCP versus UDP, and practise subnetting by hand until the powers of two come automatically. In the middle days, trace one full web request (Question 11) on paper, then capture a real one using a packet analyser such as Wireshark and watch the DNS query, handshake and TLS hello appear. In the last days, build a small lab. The free Packet Tracer simulator from Cisco Networking Academy is excellent for this, and you can also run a few Linux virtual machines. Break something on purpose, then fix it using the ping ladder.

Nothing replaces hands-on practice. The people who stand out are the ones who say “when I set this up at home, I noticed…” because that cannot be memorised.

Test yourself: five-question mock round

Tap a question to reveal the answer. The correct option is marked.

A /26 network holds how many usable host addresses?
  1. 64
  2. 62
  3. 30
  4. 254

A /26 has 2^(32-26) = 64 addresses. Two are reserved for the network and broadcast addresses, leaving 62.

Your laptop shows 169.254.12.7 and has no internet. What most likely failed?
  1. DNS
  2. The website
  3. DHCP, so no address was assigned
  4. TLS

169.254.x.x is the link-local fallback used when no DHCP server answers.

A router has routes for 10.0.0.0/8, 10.1.0.0/16 and 0.0.0.0/0. Where does a packet to 10.1.5.5 go?
  1. The 10.1.0.0/16 route
  2. The 10.0.0.0/8 route
  3. The default route
  4. It is dropped

All three match, but the longest prefix (/16) is the most specific, so it wins.

Which device forwards frames using MAC addresses?
  1. Hub
  2. Router
  3. Firewall
  4. Switch

A switch is a layer 2 device that learns MAC addresses and sends each frame only to the right port.

What are the three messages in the TCP handshake, in order?
  1. SYN, ACK, SYN-ACK
  2. SYN, SYN-ACK, ACK
  3. ACK, SYN, SYN-ACK
  4. SYN-ACK, SYN, ACK

The client sends SYN, the server replies SYN-ACK, and the client finishes with ACK.

Frequently asked questions

How many networking questions should I expect in an interview?

It depends on the role. For a general IT or developer job, expect a handful of fundamentals such as TCP versus UDP, DNS and the URL question. For a network engineer role, expect a long technical session with subnetting, routing and troubleshooting scenarios.

Do I need a certification like CCNA?

It helps for network engineering and support roles because it shows structured knowledge and gives you lab practice. It is rarely required for developer roles, where clear understanding of the basics matters more.

How do I practise without expensive equipment?

Use a free simulator such as Cisco Packet Tracer, run a few virtual machines on your own PC, and capture real traffic with Wireshark. Breaking and fixing a small lab teaches more than reading.

What should I do if I do not know an answer?

Say what you do know, reason from the layers, and say how you would find out. Interviewers value honest thinking much more than a confident wrong answer.

Should I memorise port numbers?

Learn the common ones: 22 SSH, 25 SMTP, 53 DNS, 80 HTTP, 443 HTTPS, 3306 MySQL and 3389 RDP. You do not need hundreds, but you do need those, and the reasoning behind them.

Is the OSI model actually used in real networks?

The internet runs on TCP/IP, but engineers use OSI layer numbers every day as shorthand for where a problem lives. That makes it worth knowing even though it is a reference model, not a protocol stack.

Key takeaways

  • Answer in three layers: a one-sentence definition, a real-world picture, then one detail from experience.
  • Know the layers cold. Switches are layer 2, routers are layer 3, and TCP and UDP are layer 4.
  • Be able to do subnet arithmetic: usable hosts = 2(32 − prefix) − 2, and the longest prefix wins in routing.
  • Tell the URL story end to end: DNS, TCP handshake, TLS, HTTP, render.
  • For troubleshooting, work from near to far with ping: loopback, gateway, public IP, domain name.
  • Practise with a real lab and a packet capture. Hands-on stories beat memorised definitions every time.
networking interview questionsOSI modelTCP vs UDPsubnettingDNSDHCPNATCCNA prep

The post Top 20 Networking Interview Questions with Plain-English Answers appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/top-20-networking-interview-questions/feed/ 0 973
What Is a Port Number? Why 80, 443 and 22 Matter https://learnwithexamples.org/what-is-a-port-number/ https://learnwithexamples.org/what-is-a-port-number/#respond Tue, 06 Oct 2026 09:58:30 +0000 https://learnwithexamples.org/?p=966 Networking basics · TCP and UDP · Security An IP address gets data to the right computer. But that computer is running dozens of programs at once: a browser, a…

The post What Is a Port Number? Why 80, 443 and 22 Matter appeared first on Learn With Examples.

]]>
Networking basics · TCP and UDP · Security

An IP address gets data to the right computer. But that computer is running dozens of programs at once: a browser, a mail app, a database, a chat client, an update service. Something has to decide which program receives which piece of data. That something is the port number, and once you understand it, firewalls, port forwarding, “address already in use” errors and half of the security advice you have ever read start making sense.

The problem ports solve

Think about what happens when you open a website while a video call is running, a music app is streaming and your email is syncing in the background. All of that traffic arrives at your laptop through one network connection, addressed to one IP address. Yet the website data ends up in the browser, the call audio in the call app, and the emails in the mail client. They never get mixed up.

The IP address cannot do that job, because it only identifies the machine. You need a second number that identifies the program or service on that machine. That number is the port.

The one-paragraph version. A port is a 16-bit number, from 0 to 65535, that tells the receiving computer which program or service should get the incoming data. An IP address is the building, and the port is the apartment number. Web servers conventionally listen on 80 (HTTP) and 443 (HTTPS), and remote-login servers on 22 (SSH). A connection is identified by the pair of IP addresses plus the pair of port numbers, which is how thousands of conversations share one network card without colliding.

An everyday analogy: the apartment building

Imagine you send a parcel to “42 Mall Road.” The courier finds the building, which is what an IP address does. But 42 Mall Road is an apartment block with a hundred flats. Without a flat number the parcel sits in the lobby. Write “Flat 443” on it and the right resident receives it.

One IP address: 203.0.113.1022SSH80HTTP443HTTPS3306MySQLEach numbered door leads to a different program running on the same machine.
One IP address, many doors. Each door is a port, and each service listens at its own.

The analogy also explains why some flat numbers are famous. Everybody knows the front desk is Flat 1, so visitors do not have to ask. Ports work the same way. If every web server on Earth listens on 443 for secure traffic, your browser can reach any of them without being told the number.

Where ports live: the transport layer

Ports belong to the transport layer of networking, and the two protocols that use them are TCP and UDP.

  • TCP sets up a connection first, guarantees delivery and keeps the data in order. Web pages, email and file transfers use it.
  • UDP just fires packets without a handshake or guarantees. It suits things where speed matters more than perfection, such as DNS lookups, live video, voice calls and games.

TCP port 53 and UDP port 53 are different doors that happen to share a number. Each protocol has its own full set of 65,536 ports, which is why you will see written forms like 443/tcp and 443/udp. In fact, modern HTTP/3 uses UDP port 443, while ordinary HTTPS uses TCP port 443.

Why exactly 0 to 65535?

The port number is stored in 16 bits in the TCP and UDP headers. Sixteen bits give 216, or 65,536 possible values, counting from zero. That is the whole reason for the limit. Port 0 is reserved and is not used for ordinary traffic, so in practice you work with 1 to 65535.

The three port ranges

The internet’s numbering authority, IANA, divides the 65,536 numbers into three zones.

Registered 1024–49151DynamicWell-known 0–1023 (1,024 ports, only 1.6% of the space)06553549152Total: 65,536 ports (16 bits). Dynamic zone: 16,384 ports.
The three port zones. Notice how small the well-known zone is compared with the whole space.
RangeNameCountWhat lives here
0 – 1023Well-known (system) ports1,024Core services: web, SSH, email, DNS. Assigned by IANA.
1024 – 49151Registered ports48,128Applications and databases, such as MySQL on 3306 or PostgreSQL on 5432.
49152 – 65535Dynamic (ephemeral) ports16,384Temporary numbers your device picks for outgoing connections.

One caution: operating systems do not all follow the IANA suggestion for temporary ports. Modern Windows uses 49152 to 65535 by default. Linux commonly uses 32768 to 60999, and you can read the exact range in /proc/sys/net/ipv4/ip_local_port_range. That is a tuning detail worth knowing when you debug connection limits.

The ports every beginner should memorise

PortServiceWhat it does
22 (TCP)SSHEncrypted remote login and file copying.
25 (TCP)SMTPMail transfer between mail servers.
53 (UDP/TCP)DNSTurns names like example.com into IP addresses.
80 (TCP)HTTPUnencrypted web traffic.
443 (TCP, UDP)HTTPSEncrypted web traffic. UDP carries HTTP/3.
587 (TCP)SMTP submissionWhere your mail app sends outgoing mail.
993 (TCP)IMAPSEncrypted mailbox access.
3306 (TCP)MySQLDefault MySQL and MariaDB database port.
3389 (TCP)RDPWindows Remote Desktop.
5432 (TCP)PostgreSQLDefault PostgreSQL database port.
6379 (TCP)RedisDefault Redis cache and data store port.

These are conventions, not laws. Nothing in physics forces a web server to listen on 80. It is simply the agreed default, and the agreement is what lets browsers and servers find each other without negotiation.

Why 80, 443 and 22 matter so much

Port 80: the original web

When you type http://example.com, your browser quietly adds :80. This is plain, unencrypted HTTP. Anyone on the path, such as the coffee shop Wi-Fi owner, can read or modify what travels over it. Today port 80 mostly survives to redirect visitors to the secure version.

Port 443: the secure web

When you type https://example.com, the browser adds :443. The same HTTP conversation happens, but wrapped in TLS encryption. This is the port that matters most for any site you run. Search engines, browsers and users all expect it. If you want to run a site that ranks and earns trust, port 443 must be open, and the certificate behind it must be valid.

Port 22: the administrator’s door

SSH is how people manage servers from afar. It is also, unfortunately, one of the most attacked doors on the internet. If you have ever put a server online and checked its logs an hour later, you have seen strangers hammering port 22 with guessed passwords. We will come back to what to do about that.

You can use any port in a URL by writing it after a colon. https://example.com:8443 tells the browser to use 8443 instead of 443. Developers do this constantly, and the reason is a ritual every programmer knows: local test servers run on ports like 3000, 5000, 8000 or 8080, so that they do not clash with the real web ports.

The key idea: a connection is four numbers

Here is the part that clears up the most confusion. When your browser connects to a web server, it uses a port on both sides. The server side is the well-known one (443). Your side is a temporary number the operating system picks from the dynamic range.

A TCP connection is uniquely identified by four values: your IP address, your port, the server’s IP address and the server’s port. Change any one of them and it is a different connection. That is how you can open ten tabs to the same website, all talking to the same server on the same port 443, without the answers colliding. Each tab uses a different source port on your side.

Tab 1my port 52114Tab 2my port 52115Tab 3my port 52116203.0.113.10server port 443 (HTTPS)Same server, same port 443. Each connection differs by the visitor’s port.
Three browser tabs, one server door. The server tells the conversations apart by the visitor’s port numbers.

See it for yourself in about twenty lines of Python

I like proving things in code rather than asking you to believe them. The script below starts a small server, connects to it three times, and prints which ports each side used. Then it tries to start a second server on the same port.

import socket, threading

# 1. A server listens on one port. We let the OS pick a free one (port 0).
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 0))
server.listen()
host, port = server.getsockname()
print("server listening on port", port)

# 2. Three clients connect to that single server port.
def serve():
    for _ in range(3):
        conn, addr = server.accept()
        conn.close()
threading.Thread(target=serve, daemon=True).start()

for n in range(3):
    c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    c.connect((host, port))
    print(f"client {n+1}: my port {c.getsockname()[1]} -> server port {c.getpeername()[1]}")
    c.close()

# 3. A second server cannot grab the same port.
dup = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    dup.bind((host, port))
except OSError as e:
    print("second bind failed:", e.strerror)

This is the output from one run on my machine. Your numbers will differ, because the operating system picks them:

server listening on port 54875
client 1: my port 47676 -> server port 54875
client 2: my port 47684 -> server port 54875
client 3: my port 47700 -> server port 54875
second bind failed: Address already in use

Three things are worth noticing. First, the server uses one port, 54875 in this run, for all three clients. Second, each client received a different temporary port of its own. Third, the attempt to bind a second server to the same address and port failed with “Address already in use.” Only one program can listen on a given port at a time, which explains an error that confuses beginners every single week.

The error you will meet one day. “Address already in use” or “port 3000 is already allocated” almost always means a previous copy of your program is still running, or another application owns that port. Find the owner with the commands later in this article, stop it, and try again.

The same idea in five real settings

Click a tab to see ports at work in different places. No reload, nothing to install.

Browsing the web

You type a web address and press enter. You never type a port, yet one is used on every request.

You typehttps://…
Port443
Fallback80
HTTP/3UDP 443

What happens with ports. With no port in the address, the browser assumes 80 for http and 443 for https. A site on port 80 usually just redirects you to 443. Newer browsers may also try HTTP/3, which uses UDP port 443, and fall back to TCP if that fails. If you ever see a site at :8443 or :8080, the owner chose a non-default port.

Logging in to a server

A developer manages a rented server from home. They connect with a secure shell, and their password-guessing visitors do the same.

ServiceSSH
Port22
Commandssh user@host
RiskBrute force

What happens with ports. SSH listens on 22 by default, so every scanner on the internet knocks there. Sensible practice is key-based login, no root login, and a firewall rule that allows 22 only from known addresses. To use another port, you write ssh -p 2222 user@host. It lowers log noise but is not a security measure.

Sending and reading email

Your phone’s mail app needs to send a message and fetch new ones.

Send587 or 465
Server-to-server25
Read993 or 995
Secure?Use TLS

What happens with ports. Mail uses several ports because it has several jobs. Your app submits outgoing mail on 587 (or 465 with immediate TLS). Mail servers pass messages between each other on 25. For reading, IMAP over TLS uses 993 and POP3 over TLS uses 995. Many hosting providers block outgoing port 25 from ordinary customers to cut spam, so a mail setup that works on a laptop may fail on a cloud server.

Databases

A web app stores its data in a database on the same server, or on a neighbouring one.

MySQL3306
PostgreSQL5432
Redis6379
Expose?Rarely

What happens with ports. Databases listen on their own registered ports, and the app connects to them. The golden rule is to bind them to a private address and block them in the firewall, so only the application server can reach them. Unprotected database ports on the public internet are found and attacked within hours, which is why every serious guide says to keep them closed.

Gaming and home servers

You host a game server on your PC so friends can join from their homes.

ExampleMinecraft
Port25565
NeedsForwarding
AlsoPC firewall

What happens with ports. A common Java Minecraft server listens on 25565. Your friends connect to your public IP on that port, but your router drops the unsolicited traffic until you forward public port 25565 to the PC’s private address. Then allow the same port in the PC’s own firewall. Providers that put many homes behind shared addresses can block this entirely, in which case a hosted server or a relay service is the workaround.

How your router uses ports: NAT in plain English

Your home has one public IP address from your internet provider, yet a dozen devices share it. How do replies find the right device? The router performs NAT, network address translation, and ports are the trick that makes it work.

Suppose your phone (192.168.1.20) opens a connection to a web server from its local port 51000. The router rewrites the outgoing packet so it appears to come from the router’s own public address, using its own chosen port, say 40001. It remembers the pairing in a table. When the reply returns to port 40001, it looks it up and forwards the data to the phone at 192.168.1.20 port 51000. Your laptop doing the same thing would get a different public port.

Device (private)Private portRouter (public) portDestination
192.168.1.20 phone5100040001example.com:443
192.168.1.31 laptop5100040002example.com:443
192.168.1.44 TV4950040003video.example.net:443

The numbers in the table are illustrative, since real routers pick their own. Notice that the phone and laptop both used private port 51000 and nothing broke. The router separates them by assigning different public ports.

Port forwarding: the reverse trick

NAT works naturally for connections that start inside your home. Connections that start outside have a problem: the router has no table entry, so it drops them. If you want a friend to join a game server running on your PC, you create a port forwarding rule: “anything arriving on public port 25565 goes to 192.168.1.50, port 25565.” That is exactly what the home-router tab above shows.

Firewalls: deciding which doors are open

A firewall is largely a list of rules about ports. A typical server firewall says: allow incoming 443, allow incoming 22 only from my office, and drop everything else. Because a program can only receive connections if something is listening, closing a port you do not need means that if the software behind it has a flaw, the flaw is unreachable.

When you scan a machine for open ports, there are usually three results:

  • Open. A program is listening and accepted the connection.
  • Closed. The machine is reachable, but nothing listens there, and it politely refuses.
  • Filtered. A firewall dropped the attempt, so you get no answer at all.

The practical rule I teach every junior: every open port is a promise to answer strangers. Keep that list as short as you can.

Commands to see ports on your own machine

GoalCommandNotes
List listening ports (Linux)ss -tulpnShows protocol, port and the program. Needs sudo to see other users’ programs.
List listening ports (Windows)netstat -anoThe last column is the process ID. Match it in Task Manager.
Who owns port 3000? (macOS, Linux)lsof -i :3000Prints the program and its process ID.
Test a remote port (Windows PowerShell)Test-NetConnection host -Port 443Reports whether the TCP connection succeeded.
Test a remote port (Linux, macOS)nc -zv host 443Needs netcat installed.

Tool options vary slightly between systems and versions, so treat these as reliable starting points. Only scan machines you own or have permission to test. Scanning other people’s networks can break rules or laws.

Limits you can actually hit: running out of ports

Because each outgoing connection needs a temporary port, a single client talking to a single server address and port has a ceiling. With Windows’ default dynamic range of 49152 to 65535, that is 16,384 simultaneous connections. With Linux’s common default of 32768 to 60999, it is 28,232. After that, new connections fail until old ones close.

Most users never see this. Busy servers and load balancers do, and the same arithmetic hits NAT gateways that funnel thousands of devices through one public address. When people say a service “ran out of ephemeral ports,” this is what they mean. The usual fixes are reusing connections (keep-alive and connection pooling), widening the range, or adding more addresses.

Security myths about ports

Myth: changing the SSH port makes it secure

Moving SSH from 22 to something obscure reduces noise in your logs because the lazy scanners that probe only port 22 stop finding you. It does not stop a determined scanner, which checks all ports in minutes. Real protection comes from key-based login instead of passwords, disabling root login, keeping software updated, and restricting who may connect at all. Treat a port change as tidiness, not security.

Myth: a closed port means the machine is invisible

A closed port still reveals that the machine exists. Only a firewall that silently drops traffic hides that, and even then the machine can leak information in other ways.

Myth: databases are safe on their default port because nobody knows the number

Everybody knows the number. MySQL on 3306, PostgreSQL on 5432, Redis on 6379 and MongoDB on 27017 are scanned constantly. A database should normally listen only on a private interface, with the firewall blocking public access.

Common mistakes beginners make

  • Confusing the port with the protocol. Port 443 is conventionally HTTPS, but a program can run anything on any port. The convention is not enforced.
  • Forgetting TCP versus UDP. Opening TCP 53 in a firewall does nothing for DNS queries that use UDP 53.
  • Opening a port without checking what listens behind it. You have just exposed that program to the whole internet.
  • Forwarding a port on the router but not opening it on the PC firewall. The traffic arrives and is dropped by the last gate.
  • Assuming a number above 1023 needs no thought. Registered ports can be just as dangerous as well-known ones when they hold a database.
  • Running a second copy of a server and ignoring “Address already in use.” Something already owns that port.

Test yourself

Tap a question to reveal the answer. The correct option is marked.

How many bits is a TCP or UDP port number, and what is the highest port?
  1. 8 bits, 255
  2. 32 bits, 4,294,967,295
  3. 16 bits, 65535
  4. 12 bits, 4095

Sixteen bits give 65,536 values, 0 through 65535.

You type https://example.com with no port. Which port does your browser use?
  1. 80
  2. 443
  3. 22
  4. 8080

The https scheme defaults to 443. Plain http defaults to 80.

Ten browser tabs open connections to the same server on port 443. How does the server tell them apart?
  1. By the website address
  2. By the tab title
  3. It cannot, so they share one connection
  4. By the different source ports on the visitor’s side

A connection is identified by both IP addresses and both ports. Each tab uses its own temporary source port.

Your program fails with “Address already in use” on port 3000. What is the most likely cause?
  1. Another program, maybe an earlier copy of yours, is already listening on 3000
  2. Port 3000 is reserved by IANA
  3. Your internet is down
  4. TCP does not allow ports above 1023

Only one program can listen on a given address and port. Find the owner with lsof, ss or netstat.

Which statement about changing the SSH port from 22 is true?
  1. It makes SSH impossible to attack
  2. It reduces log noise from lazy scanners but is not real security
  3. It is required by law
  4. It disables password logins

A full port scan finds any port in minutes. Real protection is key-based login, updates and firewall rules.

Frequently asked questions

What is a port number in simple words?

A number that tells a computer which program should receive incoming data. The IP address finds the machine, and the port finds the program on it.

What is the difference between port 80 and port 443?

Port 80 is the default for plain HTTP, which is unencrypted. Port 443 is the default for HTTPS, which wraps the same web traffic in TLS encryption. Modern sites use 443 and redirect 80 to it.

Is a port a physical thing?

No. It is just a number in the TCP or UDP header that the operating system uses to route data to the right program. It is not a hardware socket, even though a network cable plug is also sometimes called a port.

Can I use any port I want for my own program?

Yes, within limits. Avoid the well-known range below 1024 for personal projects, since on many systems those need extra privileges, and check that the port is not already used. Ports from about 1024 up are the usual choice for custom apps.

Are open ports dangerous?

An open port is a program accepting connections from the network. It is only as risky as the program behind it and who can reach it. Keep open only what you need, patch the software, and restrict access with a firewall.

What is the difference between TCP and UDP ports?

They are two separate sets of 65,536 numbers. TCP 53 and UDP 53 are different doors. TCP is reliable and ordered, UDP is faster with no guarantees, and some services, like DNS, use both.

Key takeaways

  • A port is a number from 0 to 65535 that tells a computer which program should receive incoming data. An IP address is the building, a port is the apartment.
  • Ports 80 (HTTP), 443 (HTTPS) and 22 (SSH) are conventions that let clients find services without negotiating.
  • A connection is identified by four values: both IP addresses and both port numbers. That is how many tabs share one server port.
  • Only one program can listen on a given port at a time, which causes “Address already in use.”
  • Routers use ports to let many devices share one public address, and port forwarding opens a door from outside.
  • Every open port is a promise to answer strangers. Keep the list short, and never rely on an obscure port number as security.
port numberport 443port 80SSH port 22TCPUDPfirewallport forwarding

The post What Is a Port Number? Why 80, 443 and 22 Matter appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-is-a-port-number/feed/ 0 966
What Is DHCP? How Your Device Gets an IP Address Automatically https://learnwithexamples.org/what-is-dhcp/ https://learnwithexamples.org/what-is-dhcp/#respond Tue, 06 Oct 2026 09:44:23 +0000 https://learnwithexamples.org/?p=963 You walk into a café, tap the Wi-Fi name, and within a second the web works. Nobody typed an address, picked a gateway or told your phone where to find…

The post What Is DHCP? How Your Device Gets an IP Address Automatically appeared first on Learn With Examples.

]]>

You walk into a café, tap the Wi-Fi name, and within a second the web works. Nobody typed an address, picked a gateway or told your phone where to find a DNS server. Behind that second sits a short, polite conversation between your phone and a small piece of software called a DHCP server. This article walks through that conversation, step by step, with real examples and a simulation I ran to show what happens when it goes wrong.

The problem DHCP solves

Every device on a network needs an IP address, which is the number other devices use to send it data. If you set one by hand, you have to pick a number nobody else is using, enter the right subnet mask, the right gateway, and at least one DNS server. Get one digit wrong and the device either cannot talk to anyone or, worse, collides with another device and knocks it offline.

I have done this by hand on more machines than I care to count, back when a small office meant a spreadsheet of addresses taped inside the server cabinet. It works for ten machines. It collapses at a hundred, and it is hopeless for phones that join and leave a network several times a day.

The fix is DHCP, the Dynamic Host Configuration Protocol. A DHCP server owns a range of addresses and a set of settings. Any device that joins the network asks for them, receives a loan of one address, and uses it until the loan runs out. The key word is loan, and it explains almost everything else in this article.

The one-paragraph version. DHCP automatically gives a device an IP address and the other settings it needs (subnet mask, default gateway, DNS servers) when it joins a network. The exchange has four messages, nicknamed DORA: Discover, Offer, Request, Acknowledge. The address is leased for a limited time, and the device renews it before it expires. At home, your router is the DHCP server.

An everyday analogy: the hotel front desk

Picture a hotel with fifty rooms. You arrive with a suitcase and no room number. You do not walk the corridors trying doors. You go to the front desk, and the clerk checks which rooms are free, assigns you one, and hands over a key card that works until checkout. If you stay longer, you stop by the desk and extend it. If you leave without telling anyone, the key card simply stops working at checkout time and the room goes back into the pool.

Map it across: the hotel is the network, the rooms are IP addresses, the guest is your device, and the clerk is the DHCP server. The checkout time is the lease. That last detail matters more than it looks, and we will see why when the café runs out of rooms.

What exactly does a DHCP server hand out?

An IP address is only the headline. A device usually receives a small bundle of settings, delivered as numbered “options” inside the DHCP messages.

SettingExampleWhat it is for
IP address192.168.1.134Your device’s identity on this network.
Subnet mask255.255.255.0Tells the device which addresses are on the same local network.
Default gateway192.168.1.1The router that carries traffic out to the internet.
DNS servers192.168.1.1Where to look up names like example.com. At home, this is often the router itself, which forwards on.
Lease time24 hoursHow long the device may keep this address before renewing.

The ordinary home values above are only an example. Many routers use 192.168.0.x or 10.0.0.x instead, and lease times vary by manufacturer and by network. There are many more options (a domain name, time servers, boot file locations for network booting), but these five are the ones you will see in daily life.

The big question: how can you ask for an address when you have none?

Here is the puzzle that makes DHCP clever. Your phone has just joined the Wi-Fi. It has no IP address, no idea what the network looks like, and no idea where the DHCP server is. How do you send a message to someone you cannot address?

The answer is broadcast. The phone sends its first message from the address 0.0.0.0 (“I am nobody yet”) to 255.255.255.255 (“everybody on this local network”). It does not know who the server is, so it shouts to the whole room. Every device on the local network hears it, but only a DHCP server answers. DHCP runs over UDP, with clients using port 68 and servers using port 67.

DORA: the four-message conversation

Network engineers use the nickname DORA for the four steps. Here is the whole exchange.

CLIENTDHCP SERVER1 DISCOVERBroadcast: anyone have an address for me?2 OFFERServer: how about 192.168.1.134?3 REQUESTBroadcast: yes, I accept that offer4 ACKNOWLEDGEServer: confirmed, lease starts nowClient uses 0.0.0.0 until step 4. Client port 68, server port 67 (UDP).
The four DHCP messages. The first two are broadcast because the client has no address yet.

1. Discover

The client broadcasts: “Is there a DHCP server out there? I need an address.” The message carries the client’s hardware (MAC) address so the server knows who is asking.

2. Offer

A DHCP server picks a free address from its pool and replies: “I can lend you 192.168.1.134, with this mask, this gateway, these DNS servers, for 24 hours.” Notice it is an offer, not a grant. The address is held aside for the client, but the deal is not done.

3. Request

The client says: “Yes, I would like that address from that server.” This message is still broadcast, and that is deliberate. If two DHCP servers both made offers, the broadcast tells every server which offer the client accepted, so the others can release the address they had reserved.

4. Acknowledge

The server confirms: “It is yours.” Only now does the client configure its network interface with the address. The conversation takes a fraction of a second on a healthy network.

If you remember one thing: Discover and Request come from the client, Offer and Acknowledge come from the server. A common exam and interview trap is mixing up Offer (a proposal) with Acknowledge (the final confirmation).

The lease: an address is borrowed, not owned

When the server says “24 hours,” the clock starts. The client does not wait until the last second. It follows two timers defined in the DHCP standard (RFC 2131):

  • T1, the renewal time, defaults to 50 percent of the lease. The client quietly asks the same server, directly, to extend the lease.
  • T2, the rebinding time, defaults to 87.5 percent of the lease. If the original server has not answered, the client now broadcasts, asking any DHCP server to extend.
  • Expiry at 100 percent. If no server has answered, the client must stop using the address and start over with Discover.
Using the addressRenewing with the same serverAny server0 hLease granted12 hT1 renew (50%)21 hT2 rebind (87.5%)24 hExpiresLifetime of a 24-hour DHCP leaseRenewal success resets the clock. Failure at 24 h means the client must start over with Discover.
A 24-hour lease. Renewal is tried at 12 hours, rebinding at 21 hours, and the address must be given up at 24 hours.

On a normal network, renewal succeeds at the 12-hour mark and the lease clock resets. Your laptop can keep the same address for months without you noticing. The lease exists for the opposite case: devices that vanish. A phone that walks out of range never says goodbye, so the server needs a way to reclaim its address. That is what expiry does.

Let us build a tiny DHCP pool

Reading about leases is one thing. Seeing one is better. Here is a small address pool in Python that hands out addresses, renews them and reclaims expired ones. It is not a real DHCP server (there are no network packets), but it implements the same bookkeeping that real servers do.

import ipaddress
from collections import deque

class DhcpPool:
    """A tiny DHCP address pool: hand out, renew and reclaim leases."""
    def __init__(self, first, last, lease_seconds):
        a = int(ipaddress.IPv4Address(first))
        b = int(ipaddress.IPv4Address(last))
        self.free = deque(str(ipaddress.IPv4Address(i)) for i in range(a, b + 1))
        self.lease = lease_seconds
        self.leases = {}                     # mac -> (ip, expires_at)

    def reclaim(self, now):
        for mac, (ip, exp) in list(self.leases.items()):
            if exp <= now:
                del self.leases[mac]
                self.free.append(ip)         # reused last, like many servers

    def request(self, mac, now):
        self.reclaim(now)
        if mac in self.leases:               # renewal: same address, fresh clock
            ip = self.leases[mac][0]
        elif self.free:
            ip = self.free.popleft()
        else:
            return None                      # pool exhausted
        self.leases[mac] = (ip, now + self.lease)
        return ip

def timers(lease_seconds):
    """RFC 2131 defaults: renew at 50 percent, rebind at 87.5 percent."""
    return lease_seconds * 0.5, lease_seconds * 0.875

# demo
pool = DhcpPool("192.168.1.100", "192.168.1.102", lease_seconds=3600)
print("phone  ->", pool.request("aa:aa", 0))
print("laptop ->", pool.request("bb:bb", 10))
print("tv     ->", pool.request("cc:cc", 20))
print("tablet ->", pool.request("dd:dd", 30), "(pool is empty)")
print("phone renews at 1800s ->", pool.request("aa:aa", 1800))
print("tablet at 3700s ->", pool.request("dd:dd", 3700), "(laptop and tv expired)")
t1, t2 = timers(86400)
print("24h lease: renew at %.0fh, rebind at %.1fh" % (t1/3600, t2/3600))

Running it with a pool of only three addresses and a one-hour lease produces this:

phone  -> 192.168.1.100
laptop -> 192.168.1.101
tv     -> 192.168.1.102
tablet -> None (pool is empty)
phone renews at 1800s -> 192.168.1.100
tablet at 3700s -> 192.168.1.101 (laptop and tv expired)
24h lease: renew at 12h, rebind at 21.0h

Read it line by line. The first three devices get consecutive addresses. The tablet asks while the pool is empty and gets nothing, which is exactly what a real device experiences when a network runs out of addresses. The phone renews at the half-hour mark and keeps the same address. By 3,700 seconds, the laptop and TV leases have expired without anyone releasing them, so the tablet finally gets the laptop’s old address.

When the hotel runs out of rooms: a café simulation

Lease length sounds like a boring setting until you see it break something. So I simulated a café with Wi-Fi. About one new customer device joins every minute, stays for roughly half an hour on average, and leaves without telling the network. The DHCP pool has 100 addresses. I ran ten hours of café time, repeated twenty times with different random seeds, and varied only the lease length. Devices renew at the 50 percent mark while they are present, just like real ones.

Lease timePeak addresses in useDevices that could not get an address
10 min54 of 1000.0%
30 min71 of 1000.0%
1 hour95 of 1000.2%
4 hours100 of 10051.3%
24 hours100 of 10083.3%
0%25%50%75%100%0.0%10 min0.0%30 min0.2%1 hour51.3%4 hours83.3%24 hoursLease length (pool of 100 addresses, ten-hour café day, average of 20 runs)
Share of arriving devices that found the pool empty, by lease length. Same café, same crowd, same pool size.

The shape of the result is the lesson. With a 10 or 30-minute lease, nobody was turned away. At one hour, a handful of devices failed during the busiest moments. At four hours, about half of all arriving devices found no free address, and at 24 hours more than four out of five did. The crowd was identical in every run. The only difference was how long departed devices kept their addresses reserved.

The figures come from a simplified model: random arrivals, a random stay time and no early release. Real cafés have more variety, and the exact percentages will differ. The pattern will not. A short lease is the right tool for a transient crowd, and a long lease is the right tool for a stable one. Home and office networks, where the same devices come back every day, can use long leases comfortably. Hotels, airports, conferences and cafés should use short ones.

The same idea in five real settings

Click a tab to see DHCP in different places. Nothing to install and no page reload.

Home router

You buy a Wi-Fi router, plug it in and connect your phone, TV, laptop and a smart speaker. You never touch an address setting.

ServerYour router
Pool~100 addresses
LeaseOften 24 h
DNSRouter or ISP

How DHCP fits. The router runs a DHCP server by default, usually with a pool such as 192.168.1.100 to 192.168.1.199 (the exact range differs by brand). Long leases suit a home, because the same dozen devices come back every day. Look in the router’s admin page for a “connected devices” or “DHCP clients” list and you will see the leases.

Café or airport Wi-Fi

Hundreds of strangers pass through, most staying under an hour. Phones leave without any goodbye.

CrowdConstantly changing
LeaseMinutes to 1 h
PoolLarge
RiskPool runs dry

How DHCP fits. This is the café from our simulation. Public networks use short leases and wide pools so addresses of departed devices return quickly. Many also use much larger private ranges than a home network, because a /24 holds only 254 addresses.

Office with several networks

A company separates staff, guests, phones and printers into different networks for security and tidiness.

ServersOne central
RelayIP helper
ScopesOne per network
ExtrasReservations

How DHCP fits. Each network gets its own pool, called a scope, on one central DHCP server. Routers forward the broadcasts through a relay agent. Managers also add reservations for fixed gear and exclusion ranges so the pool never touches addresses set by hand.

Your ISP connection

Your home router does not come with an internet-facing address built in. It has to get one from your internet provider.

ClientYour router
ServerISP equipment
GetsWAN address
ChangesSometimes

How DHCP fits. On many cable and fibre connections, your router is itself a DHCP client on the provider’s side. It broadcasts a request, and the provider’s server leases it a public address. That is why a home address can change after a long outage. Other providers use different methods, such as PPPoE, so this varies by ISP.

Printer or NAS reservation

Your family prints from five devices. The printer is found by address, and every few weeks one laptop loses it.

DevicePrinter, NAS
Matched byMAC address
ResultFixed address
Set inDHCP server

How DHCP fits. A reservation tells the DHCP server: whenever this MAC address asks, always give it this address. The printer still uses DHCP, so nothing is typed on the device itself, but its address never moves. It is the tidiest way to get a stable address without hand-configuring anything.

Dynamic, static and reserved: three ways to get an address

DHCP is not all-or-nothing. Most real networks mix three approaches.

MethodHow the address is setBest forWatch out for
Dynamic DHCPServer picks any free address from the pool.Phones, laptops, guests, most devices.The address can change after a long absence.
DHCP reservationServer always gives the same address to a specific MAC address.Printers, NAS boxes, cameras, servers.Changing the network card changes the MAC, which breaks the match.
Static (manual)You type the address on the device itself.Routers, core infrastructure, bootstrapping.You must avoid the DHCP pool range or you risk conflicts.

My own rule after fifteen-odd years: configure a reservation on the DHCP server rather than a static address on the device whenever you can. All the addressing then lives in one place, and you can see and change it from the server. Static addresses scattered across devices are how networks accumulate mysteries.

What happens when DHCP fails?

If a device sends Discover and nobody answers, it does not give up silently. Modern operating systems fall back to a link-local address in the range 169.254.0.0 to 169.254.255.255 (defined in RFC 3927, and called APIPA on Windows). The device picks one at random in that range and checks that nobody else is using it.

That fallback only lets the device talk to other link-local devices on the same local network. There is no gateway, so there is no internet. If you ever open your network settings and see an address starting with 169.254, read it as a message: “I asked for an address, and nobody gave me one.”

Quick diagnosis. An address starting with 169.254 means DHCP did not respond. Check that the router is on, that you are on the right network, and that the DHCP service is enabled. Do not waste time hunting for DNS or website problems yet. You do not even have a valid address.

Commands you can run yourself

Seeing the lease on your own machine makes this concrete. The commands vary a little by operating system.

GoalWindowsLinux or macOS
See your current address and DHCP serveripconfig /allip addr (Linux), ipconfig getpacket en0 (macOS)
Give up the current leaseipconfig /releaseToggle the network interface off, or use your network manager’s reconnect option.
Ask for a new leaseipconfig /renewToggle the interface back on, or reconnect.

On Windows, ipconfig /all prints a “DHCP Server” line plus “Lease Obtained” and “Lease Expires” times. That is the lease we have been discussing, sitting right there on your screen. The macOS interface name (en0 here) can differ between machines, and Linux tools differ between distributions, so treat these as starting points.

Beyond one subnet: relay agents

There is an obvious catch with broadcasts. Routers do not forward them, so a DHCP broadcast stays inside its own local network. In a company with separate networks for staff, guests and printers, would you need a DHCP server in every one?

No. The trick is a DHCP relay agent, usually a setting on the router (often called “IP helper”). It listens for broadcasts on one network, wraps them in a unicast message and forwards them to a central DHCP server. The relay stamps in the address of the network the request came from, so the server knows which pool to use. One central server can then serve dozens of separate networks, each with its own address range.

Routerrelay agentStaff network10.1.0.0/24Guest network10.2.0.0/24Printer network10.3.0.0/24DHCP serverone central serverunicastBroadcasts stop at the router, so it forwards them to the server.The server picks the pool that matches the network each request came from.
A relay agent carries broadcasts from separate networks to one central DHCP server.

IPv6 and DHCPv6, briefly

Everything above is DHCP for IPv4. IPv6 networks have another automatic option called SLAAC (stateless address autoconfiguration), where a device builds its own address from information advertised by the router. DHCPv6 also exists, and networks use it when they want central control over addresses or need to pass out extra settings. The two are not rivals so much as tools, and many networks use them together. The details deserve their own article.

Security: DHCP trusts everyone

DHCP was designed for a friendlier era. A client believes the first offer it likes, with no authentication. That creates two classic problems.

Rogue DHCP servers

Someone plugs in a router, or a misconfigured device starts running a DHCP service. Clients that hear its offer first accept it, and now they receive a wrong gateway or a malicious DNS server. At best, people lose internet access and nobody can explain why. At worst, traffic is redirected through an attacker. The defence on managed switches is DHCP snooping, which only allows DHCP server messages from ports marked as trusted.

Address starvation

An attacker, or a buggy device, sends a flood of requests with fake MAC addresses until the pool is empty and real users get nothing. Switch features that limit the number of MAC addresses per port, and short leases on guest networks, reduce the damage.

Common problems and how I debug them

  • Two DHCP servers on one network. A very common home mistake is plugging a second router into the first one with its DHCP still enabled. Devices randomly get settings from either, and some end up with the wrong gateway. Turn off DHCP on one of them.
  • The 169.254 address. No reply from any server. Check cabling, Wi-Fi network, and whether the DHCP service is running.
  • Duplicate address warnings. A device with a manually typed address inside the DHCP pool range. Move the static address outside the pool, or create a reservation instead.
  • Pool exhaustion. Leases too long for the crowd, or the pool simply too small. Widen the range or shorten the lease, as in the café simulation.
  • The printer keeps “disappearing.” It got a new address after a long power-off. Give it a reservation.
  • Everything works by IP but not by name. The DHCP server handed out a bad DNS setting. Check the DNS option in the lease, not the website.

Common mistakes beginners make

  • Thinking DHCP and DNS are the same thing. DHCP assigns addresses. DNS translates names into addresses. DHCP merely tells you which DNS server to use.
  • Assuming a DHCP address is permanent. It is a lease. It often stays the same in practice, but nothing guarantees it.
  • Setting a static address inside the DHCP pool. The server may hand the same address to someone else.
  • Forgetting to exclude the router. The gateway itself should sit outside the dynamic range, typically at the start of the subnet.
  • Using a 24-hour lease on a public Wi-Fi network. You now know how that ends.

Test yourself

Tap a question to reveal the answer. The correct option is marked.

What are the four DHCP messages, in order?
  1. Request, Offer, Discover, Acknowledge
  2. Discover, Offer, Request, Acknowledge
  3. Discover, Request, Offer, Acknowledge
  4. Offer, Discover, Acknowledge, Request

Remember DORA: Discover and Request come from the client, Offer and Acknowledge from the server.

Why is the first DHCP message sent as a broadcast?
  1. Broadcasts are encrypted
  2. DHCP only works over TCP
  3. The client has no address and does not know where the server is
  4. Routers require it

With no address and no knowledge of the server, the client shouts to everyone on the local network and lets the server answer.

A lease is 8 hours. When does the client first try to renew, using the default timers?
  1. After 4 hours
  2. After 6 hours
  3. After 7 hours
  4. Only at 8 hours

T1 is 50 percent of the lease, so renewal begins at 4 hours. T2, the broadcast rebind, comes at 87.5 percent, or 7 hours.

Your laptop shows the address 169.254.37.12 and has no internet. What most likely happened?
  1. DNS is down
  2. The website is blocked
  3. The router is overheating
  4. No DHCP server answered, so it gave itself a link-local address

169.254.x.x is the link-local fallback used when DHCP does not respond. It allows only local-network chatter.

Which is the best way to give a network printer a stable address while managing everything centrally?
  1. A static address inside the DHCP pool
  2. A DHCP reservation tied to its MAC address
  3. A very short lease
  4. Turning DHCP off for the whole network

A reservation keeps the printer on DHCP but always gives it the same address, with no conflict risk and no manual typing on the device.

Frequently asked questions

What does DHCP stand for?

Dynamic Host Configuration Protocol. It automatically configures devices with an IP address and related network settings.

Is DHCP the same as DNS?

No. DHCP gives a device its address and tells it which DNS server to use. DNS is the separate service that turns names like example.com into addresses.

Will my device keep the same IP address?

Often yes in practice, because a returning device usually gets its old address back if it is still free. But a lease is not a guarantee. For a fixed address, use a DHCP reservation.

Where is the DHCP server on my home network?

In almost every case, it is your router. Some networks use a separate server or a dedicated device, and a home setup can have only one active DHCP server safely.

What happens if two DHCP servers are on one network?

Clients take whichever offer reaches them first, so devices get inconsistent settings, such as different gateways, and failures look random. Disable DHCP on one of the devices.

Should I use static IPs or DHCP?

Use DHCP for most devices. For devices that need a fixed address, prefer a DHCP reservation. Use true static addressing mainly for the router itself and a few core pieces of infrastructure, keeping those addresses outside the DHCP pool.

Key takeaways

  • DHCP automatically gives a device an IP address, subnet mask, gateway and DNS servers when it joins a network.
  • The four-step conversation is Discover, Offer, Request, Acknowledge. The first two are broadcast because the client has no address yet.
  • An address is a lease, not a gift. Clients renew at 50 percent of the lease and rebind at 87.5 percent.
  • Lease length should match the crowd. In my café simulation, a 30-minute lease turned nobody away, while a 24-hour lease turned away more than four in five devices.
  • Use reservations for printers and servers, keep static addresses outside the pool, and treat any 169.254 address as “DHCP did not answer.”
  • Relay agents let one server serve many networks, and DHCP snooping protects against rogue servers.
DHCPIP addressnetworking basicsDORADHCP leaserouterPython

The post What Is DHCP? How Your Device Gets an IP Address Automatically appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-is-dhcp/feed/ 0 963
Ransomware: How It Works and How It Spreads https://learnwithexamples.org/ransomware-how-it-works-spreads/ https://learnwithexamples.org/ransomware-how-it-works-spreads/#respond Tue, 04 Aug 2026 17:40:10 +0000 https://learnwithexamples.org/?p=848 Learn With Examples It almost never starts with a hacker in a hoodie breaking down a digital door. It starts with one password, one unpatched server, or one convincing email…

The post Ransomware: How It Works and How It Spreads appeared first on Learn With Examples.

]]>

Learn With Examples

It almost never starts with a hacker in a hoodie breaking down a digital door. It starts with one password, one unpatched server, or one convincing email — and by the time the ransom note appears, the attackers have often been inside for weeks.

Reading time13 min
LevelBeginner friendly
Includes5 real case files

Picture a Friday afternoon at a mid-sized logistics company. An accounts clerk gets an email that looks like an unpaid invoice from a supplier she deals with weekly. She opens the attachment. Nothing visibly happens, so she carries on with her day and goes home.

Nineteen days later, at 2:14 on a Sunday morning, every file server in the company locks simultaneously. Spreadsheets, delivery schedules, the customer database, even the backups on the network drive — all replaced with scrambled files and a text document explaining where to send the Bitcoin.

Those nineteen days are the part almost nobody pictures. Ransomware is not a bomb that goes off when you click. It is a burglary that ends with the locks being changed — and the burglary itself takes days or weeks, during which the intruders are quietly reading your email, finding your backups, and stealing your data before a single file is ever encrypted.

This article explains what actually happens in those weeks, how the infection gets in, and what five of the most damaging real-world attacks teach us. Everything here is defensive knowledge: how the attack chain works, so you can recognise and break it.

In one paragraph

What ransomware is

Ransomware is malicious software that makes your data unusable and sells it back to you. It scrambles your files with strong encryption, and the key needed to unscramble them is held by the attacker until you pay. Modern attacks add a second lever: before encrypting anything, they copy your sensitive data out and threaten to publish it. So even a company with perfect backups still faces a leak.

The important part for defenders: encryption is the last step. Everything before it — the break-in, the spread, the theft — is where an attack can still be stopped.

Why it stopped being about locked files

Early ransomware was crude and indiscriminate: infect as many home computers as possible, demand a few hundred dollars each, hope enough people pay. Then criminals noticed that a hospital or a factory will pay vastly more than a thousand individuals, and the whole model changed.

  • 2013 — 2015 · SPRAY AND PRAYMass email campaigns hitting individuals for a few hundred dollars. Good backups were a complete defence.
  • 2016 — 2018 · BIG GAME HUNTINGAttackers begin targeting organisations deliberately, studying revenue and pricing the ransom to fit. Demands jump into six and seven figures.
  • 2019 · DOUBLE EXTORTIONThe pivotal change: steal the data first, then encrypt. Now backups alone don’t save you — refusing to pay means your customers’ data gets published.
  • 2020 onwards · RANSOMWARE AS A SERVICEThe criminal ecosystem specialises. One group writes the software, others break into networks, others negotiate. You no longer need technical skill to run an attack.
  • 2023 onwards · EXTORTION WITHOUT ENCRYPTIONSome groups skip the encryption entirely. Stealing the data and threatening to leak it is quieter, faster, and often just as profitable.

That progression matters because it changes what “being prepared” means. Backups answer the 2015 problem. They do nothing about the 2019 one. A company today needs to survive both losing access to its data and having that data published.

The attack chain, stage by stage

Nearly every serious ransomware incident follows the same six stages. Tap through them — each stage is a place where the attack could still be caught, and knowing that is the entire point of learning the sequence.

The six stages

tap a stage
Stage 1 · Initial access

Getting through the front door

Three routes account for the overwhelming majority of break-ins: a stolen or guessed password on a remote access system without multi-factor authentication, an unpatched internet-facing server, and a convincing email that persuades someone to open something.

Real example: the Colonial Pipeline attackers in 2021 didn’t need anything sophisticated. They used a password for a disused VPN account that appeared in a batch of leaked credentials. That account had no multi-factor authentication on it.

Where it breaks: MFA everywhere, prompt patching of anything reachable from the internet, and shutting down accounts nobody uses.

Stage 2 · Establishing a foothold

Making sure they can get back in

The first thing an intruder does is make their access durable. They set up a second and third way back into the network, so losing one doesn’t lock them out. Increasingly they use ordinary administration tools that already exist on your systems, precisely because those tools don’t look suspicious.

Why it matters: this is why “we changed that password” is not a fix. If someone has been inside for two weeks, the door they came through is rarely the only one still open.

Where it breaks: endpoint monitoring that flags unusual use of legitimate admin tools, and alerting on new accounts or scheduled tasks appearing.

Stage 3 · Reconnaissance

Reading your organisation

Now they explore. Where are the file servers? Which systems would hurt most if they stopped? Where are the backups, and are they connected to the network? They read finance documents to work out what you can afford, and they check whether you have cyber insurance — because that tells them your ceiling.

The uncomfortable statistic: attackers commonly spend days to weeks inside a network before triggering anything. During that window there is nothing to see unless you are looking.

Where it breaks: network segmentation, so that compromising one laptop doesn’t grant a tour of everything, and monitoring for unusual internal scanning.

Stage 4 · Privilege escalation

Becoming the administrator

One ordinary user account isn’t enough to encrypt a company. The goal is domain administrator — the keys to everything. Attackers get there by harvesting credentials left in memory on shared machines, exploiting misconfigured permissions, or simply finding a password in a document called something like server-passwords.xlsx.

Real example: in the 2023 attack on MGM Resorts, attackers reportedly phoned the IT help desk, impersonated an employee, and talked their way into a credential reset. No exploit required — just a convincing phone call.

Where it breaks: least privilege, separate accounts for admin work, and strict identity verification for help-desk resets.

Stage 5 · Data theft

Copying everything out first

Before anything is locked, the valuable data leaves — customer records, contracts, HR files, source code. Often it is uploaded to ordinary cloud storage services, because that traffic blends in with normal business use.

Why this stage exists: it is the insurance policy against your backups. If you restore everything and refuse to pay, they still hold your data and can publish it. This is what turned ransomware from an IT problem into a legal and reputational one.

Where it breaks: monitoring for large outbound transfers, and controls on which cloud services can be reached from inside the network.

Stage 6 · Encryption and extortion

The part everybody pictures

Only now do files get encrypted, usually at night or over a holiday weekend when nobody is watching. Backups are deliberately destroyed or encrypted first. Then the ransom note appears, typically with a countdown and a link to a private chat with the attackers.

The timing is deliberate: attacks cluster around Friday nights, public holidays, and long weekends. Fewer staff, slower detection, more hours to finish the job.

Where it breaks: offline or immutable backups that cannot be reached from the network, and a tested recovery plan — the emphasis being firmly on tested.

Stages 1 to 5 are invisible to most organisations. Stage 6 is impossible to miss. Nearly all the opportunity to prevent a disaster sits in the part nobody sees.

By the time you can see ransomware, you are not preventing an attack any more. You are recovering from one that finished.

How it actually spreads

Two different questions get muddled here: how attackers get into an organisation, and how the infection moves within one. They have different answers.

Getting in: the three doors

Where attacks begin

industry incident reports, broadly consistent year to year
Stolen credentials & exposed remote accesslargest single category
Unpatched internet-facing softwarevery large
Phishing & malicious attachmentsvery large
Supply chain & trusted software updatesrarer, far bigger blast radius

Proportions vary between reports and years, but the ranking is stubbornly stable: credentials and unpatched internet-facing systems consistently beat phishing as the way in.

That last point surprises people, because security training focuses so heavily on suspicious emails. Phishing is a genuine and major route — but a remote access portal with no multi-factor authentication is a permanently open door that requires no one to make a mistake at all. It just needs one password to appear in any of the billions already circulating from previous breaches.

Moving inside: how one machine becomes five hundred

METHOD 01

Stolen credentials

The most common by far. With an administrator password, attackers simply log in to other machines. Nothing is “hacked” — they use the same tools your IT team does.

METHOD 02

Management tools

Software built to push updates to every computer at once is perfect for pushing ransomware to every computer at once. Attackers actively hunt for it.

METHOD 03

Network shares

Mapped drives are a gift. Anything a compromised user can write to, ransomware can encrypt — including that “backup” folder on the shared server.

METHOD 04

Worm-like exploits

Rare but devastating. A flaw needing no human interaction lets the infection jump machine to machine automatically, in minutes rather than days.

The backup trap. A backup drive that is permanently connected and writable is not a backup as far as ransomware is concerned — it is just more files to encrypt. Attackers look for backups deliberately and destroy them first, because a company that can restore is a company that won’t pay. Backups must be offline, immutable, or in a separate account the compromised network cannot reach.

Five real attacks, and what each one teaches

These are the incidents worth knowing, not because they were the most sophisticated, but because each exposed a different weakness.

Case files

tap a case
May 2017 · global

WannaCry — the patch nobody applied

WannaCry spread itself. It used a flaw in an old Windows file-sharing protocol that let it jump from machine to machine with no human involvement, infecting well over 200,000 computers across 150 countries in a couple of days. Britain’s NHS was hit hard: ambulances diverted, thousands of appointments and operations cancelled.

The detail that stings: Microsoft had released the patch two months earlier. Every organisation that applied updates promptly was immune. The outbreak was eventually slowed when a researcher registered a domain name found in the code that acted as an accidental kill switch.

Lesson: patching internet-facing and networked systems is not administrative housekeeping. It is the single highest-return security activity most organisations can do.

June 2017 · global

NotPetya — the one that wasn’t really ransomware

NotPetya arrived through a poisoned update to a Ukrainian tax accounting package that most companies doing business in Ukraine were required to use. It looked like ransomware and demanded payment — but the encryption was designed to be irreversible. Paying achieved nothing. It was destruction dressed as extortion.

Shipping giant Maersk lost virtually its entire global IT estate and rebuilt roughly 4,000 servers and 45,000 computers in about ten days. Total worldwide damages have been estimated at around $10 billion, making it the costliest cyberattack in history.

Lesson: software you trust and update automatically is a route into your network. And a “ransom” is not always a real offer — recovery capability matters more than negotiating ability.

May 2021 · United States

Colonial Pipeline — one password, one country queuing for fuel

The largest fuel pipeline in the US, carrying nearly half the East Coast’s supply, shut down for around six days. Panic buying emptied filling stations across several states and a state of emergency was declared.

The entry point was a single VPN account that was no longer in use, protected by a password that had leaked in an earlier breach elsewhere, with no multi-factor authentication. The company paid roughly $4.4 million in Bitcoin; US authorities later recovered a substantial portion of it. Notably, the pipeline itself was shut down as a precaution — the billing systems were the ones affected.

Lesson: disused accounts are live doors, reused passwords eventually surface in a leak, and MFA on remote access would have ended this attack before it began.

July 2021 · global

Kaseya — attacking a thousand companies at once

Rather than break into companies one by one, attackers compromised a tool that IT service providers use to manage their clients’ computers remotely. The ransomware was then pushed out through that trusted channel to roughly 1,500 downstream businesses in a single stroke — including a Swedish supermarket chain that had to close around 800 stores because its tills stopped working.

The attack landed on the Friday of a long holiday weekend in the US, when response teams were thinnest. That timing was not a coincidence.

Lesson: your security includes your suppliers’ security. Any vendor with remote access into your systems is part of your attack surface.

February 2024 · United States

Change Healthcare — the most expensive lesson in MFA

Change Healthcare processes a large share of American medical claims. When it was hit, pharmacies could not verify insurance, providers could not bill, and parts of the healthcare payment system stalled for weeks. Parent company UnitedHealth ultimately reported costs running into billions of dollars, and the breach affected the data of well over a hundred million people.

The way in was a remote access portal without multi-factor authentication. A $22 million ransom was paid for a promise to delete the stolen data — then the criminal group collapsed in an apparent exit scam, the stolen data moved to a second gang, and a fresh extortion demand followed.

Lesson: paying buys a promise from criminals, not a guarantee. And when one company sits at the centre of an industry, its security is everyone’s problem.

Why it keeps happening: the business behind it

Ransomware persists because it has become an industry with specialised roles, not a hobby for lone hackers.

RoleWhat they doWhy it matters
DevelopersBuild and maintain the software, run the leak site and payment infrastructureThey rent it out and take a cut — they rarely attack anyone directly
AffiliatesDo the actual break-ins using the rented toolkitYou don’t need technical depth to run an attack any more
Access brokersBreak into networks and sell that access to whoever wants itYour network can be sold as a product before anyone encrypts anything
NegotiatorsHandle the victim chat, apply pressure, arrange paymentProfessionalised, scripted, and experienced at reading desperation

This division of labour explains a lot. It explains why attacks are so consistent in method — affiliates follow playbooks. It explains why groups reappear under new names after being disrupted — the people move, the brand changes. And it explains why paying keeps the machine running: every payment funds the next round of development.

Should victims pay?

This is a decision for the organisation with legal counsel and law enforcement, and the honest position is that there is no clean answer. What can be said factually:

  • Paying buys a decryption key that often works imperfectly — restoration from decryptors is typically slow and incomplete.
  • Paying for deletion of stolen data buys a promise. The Change Healthcare case shows what that promise can be worth.
  • Organisations that pay are disproportionately targeted again, sometimes by the same affiliate.
  • In some jurisdictions, payments to sanctioned groups carry legal exposure of their own.
  • Recovery from clean backups is usually faster than decryption — when those backups exist and have been tested.

Which is why the real decision is made long before the ransom note: an organisation that can restore has options, and an organisation that cannot has only one.

Defending against it, in priority order

Tick these off as you read — they’re ordered by how much protection they buy per unit of effort, and the first three stop the majority of real-world attacks outright.

Defence checklist

tap to tick

If it happens anyway. Isolate affected machines from the network but don’t power them off — useful evidence lives in memory. Don’t delete anything. Contact law enforcement and your cyber insurer early, since both may have resources and requirements you need. Assume data was stolen and plan your notifications accordingly. And resist the urge to restore in a rush: rebuilding into a network the attacker still has access to is a well-trodden way to be encrypted twice.

Four myths worth deleting

“We’re too small to be a target.”

Most attacks aren’t targeted at all — they’re opportunistic, driven by automated scanning for exposed systems and weak credentials. Small organisations are attacked constantly, precisely because they’re less likely to have monitoring, and a smaller ransom is still profit for a group running dozens of attacks a month.

“Our antivirus will catch it.”

Antivirus catches known malicious files. It struggles with an attacker who logs in with valid credentials and uses your own administration tools — which is exactly what most modern intrusions look like. Detection has to cover behaviour, not just files.

“We have backups, so we’re fine.”

Backups solve half the problem, and only if they’re offline and tested. They do nothing about stolen data being published, and connected backups are routinely destroyed by the attacker before encryption begins.

“It happens instantly when someone clicks.”

Encryption is the final act, often days or weeks after the initial break-in. That gap is the defender’s real opportunity — every attack that gets detected during it is an attack you never hear about.

Check yourself

Five questions. Open each to check — the correct option is marked.

1. At what point in a ransomware attack does encryption happen?
  • Immediately when someone clicks a link
  • Last, often days or weeks after the initial break-in
  • Before the attacker gets administrator access
  • Only after the ransom is refused

Encryption is stage six of six. Everything before it is invisible to most organisations, and it’s where the attack can still be stopped.

2. What was the entry point in the Colonial Pipeline attack?
  • A zero-day exploit in industrial control systems
  • A malicious email attachment opened by an executive
  • A disused VPN account with a leaked password and no MFA
  • A compromised software update

No sophistication required. One old account, one reused password, no second factor — and half the US East Coast’s fuel supply stopped moving.

3. Why do attackers steal data before encrypting it?
  • Encryption doesn’t work without a copy
  • So that good backups don’t remove the victim’s reason to pay
  • To test whether the files are valuable
  • It makes the encryption faster

Double extortion is the answer to backups. Restore everything and refuse to pay, and they publish your customers’ data instead.

4. Which single control would have prevented the most cases in this article?
  • Antivirus software
  • Employee phishing training
  • Multi-factor authentication on internet-facing access
  • A stronger firewall

Colonial Pipeline and Change Healthcare both came down to remote access without MFA. It’s unglamorous and it’s the highest-value control most organisations can deploy.

5. Why is a permanently connected backup drive a problem?
  • It wears out faster
  • Ransomware encrypts anything writable, and attackers destroy backups first
  • It slows the network down
  • It isn’t a problem

Attackers hunt for backups deliberately, because a company that can restore is a company that won’t pay. Offline or immutable is the requirement.

Frequently asked questions

How does ransomware get onto a computer?

Most commonly through stolen or guessed credentials on remote access systems without multi-factor authentication, through unpatched internet-facing software, or through a convincing email attachment or link. Less often, through a compromised software update from a trusted supplier.

How long does a ransomware attack take?

The encryption itself takes hours. The intrusion leading up to it commonly takes days to weeks, during which attackers explore the network, escalate their access, and copy data out. The visible part is the very end of a long, quiet process.

Can encrypted files be recovered without paying?

Sometimes. Free decryptors exist for older or flawed ransomware families, and projects like No More Ransom collect them. For current strains with correctly implemented encryption, breaking it is not realistic — recovery means restoring from backups.

Does paying the ransom actually work?

Partially, often. Decryption keys usually work but restoration is typically slow and imperfect, and promises to delete stolen data are unverifiable — the Change Healthcare case ended with a second gang demanding a second ransom for the same data. Paying also marks an organisation as willing to pay.

What should a small business do first?

Turn on multi-factor authentication everywhere, especially email and any remote access. Then get backups that are disconnected from the network and actually test restoring from them. Those two steps cost very little and remove the majority of realistic attack paths.

The takeaway

Ransomware is not really a story about encryption. It’s a story about access — how someone gets in, how far they can move once inside, and how long they can stay before anyone notices. The encryption at the end is just the invoice.

Which is why the defences that matter are so unglamorous. Not clever software, but multi-factor authentication on the front door, patches applied on time, backups the attacker can’t reach, and a plan that has been rehearsed before it’s needed. Colonial Pipeline, Change Healthcare, WannaCry — every one of them turns on something a checklist would have caught.

If you take one action after reading this, make it the smallest one: check whether multi-factor authentication is switched on for your email and any remote access you use. That single setting appears in the story of more prevented attacks than anything else in this article.

ransomwarecybersecuritymalwarephishingdata breachMFA

The post Ransomware: How It Works and How It Spreads appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/ransomware-how-it-works-spreads/feed/ 0 848
OSI Model Explained: 7 Layers with Real-World Examples https://learnwithexamples.org/osi-model-explained/ https://learnwithexamples.org/osi-model-explained/#respond Fri, 19 Sep 2025 08:45:09 +0000 https://learnwithexamples.org/?p=592 OSI Model Explained: 7 Layers with Real-World Examples Understanding Network Communication The OSI (Open Systems Interconnection) model is a conceptual framework that standardizes the communication functions of a telecommunication or…

The post OSI Model Explained: 7 Layers with Real-World Examples appeared first on Learn With Examples.

]]>
OSI Model Explained: 7 Layers with Real-World Examples

Understanding Network Communication

The OSI (Open Systems Interconnection) model is a conceptual framework that standardizes the communication functions of a telecommunication or computing system. Think of it as a blueprint that helps different computer systems communicate with each other, regardless of their underlying architecture.

What is the OSI Model?

Imagine you’re sending a letter to a friend in another country. You write the message, put it in an envelope, address it, take it to the post office, and rely on various transportation methods to deliver it. The OSI model works similarly for digital communication, breaking down the complex process of network communication into seven distinct layers, each with specific responsibilities.

Developed by the International Organization for Standardization (ISO) in 1984, the OSI model serves as a universal reference point for understanding how data travels from one computer to another across a network. Each layer performs specific functions and communicates only with the layers directly above and below it, creating a structured approach to network communication.

The 7 Layers of the OSI Model

Click on each layer to explore its functions and real-world examples:

Layer 7: Application Layer
Layer 6: Presentation Layer
Layer 5: Session Layer
Layer 4: Transport Layer
Layer 3: Network Layer
Layer 2: Data Link Layer
Layer 1: Physical Layer

Layer 7: Application Layer

Function: This is the layer closest to the user. It provides network services directly to applications and end-users.

What it does: Handles high-level protocols, representation, encoding, and dialog control. It’s where user applications interact with the network.

Real-World Examples:

  • Web Browsing: When you type www.google.com in your browser
  • Email: Sending and receiving emails through Gmail or Outlook
  • File Transfer: Uploading files to Google Drive or Dropbox
  • Video Streaming: Watching videos on YouTube or Netflix

Common Protocols:

HTTP/HTTPS SMTP FTP DNS DHCP

Layer 6: Presentation Layer

Function: Translates data between the application layer and the network. It’s responsible for data encryption, compression, and format conversion.

What it does: Ensures that data sent from one system can be understood by another, handling different data formats and encryption.

Real-World Examples:

  • Image Formats: Converting JPEG to PNG or displaying images in web browsers
  • Data Encryption: HTTPS encryption when you shop online
  • Text Encoding: Converting ASCII to Unicode for international characters
  • Video Compression: MP4, AVI format handling in media players

Common Protocols:

SSL/TLS JPEG GIF MPEG ASCII

Layer 5: Session Layer

Function: Manages sessions or connections between applications. It establishes, manages, and terminates connections between local and remote applications.

What it does: Controls dialogues and connections, manages full-duplex, half-duplex, or simplex communications.

Real-World Examples:

  • Video Calls: Zoom or Skype maintaining connection during a call
  • Database Sessions: SQL database connections staying active
  • Web Sessions: Shopping cart maintaining items while you browse
  • Remote Desktop: RDP sessions for remote computer access

Common Protocols:

NetBIOS RPC SQL NFS PPTP

Layer 4: Transport Layer

Function: Ensures reliable data transfer between end systems. It handles error correction, flow control, and retransmission of lost data.

What it does: Breaks large messages into smaller packets and reassembles them at the destination, ensuring data integrity.

Real-World Examples:

  • Web Traffic: TCP ensuring all webpage data arrives correctly
  • File Downloads: Ensuring downloaded files are complete and uncorrupted
  • Live Streaming: UDP allowing real-time video with some data loss tolerance
  • Online Gaming: UDP for fast response times in multiplayer games

Common Protocols:

TCP UDP SCTP SPX

Layer 3: Network Layer

Function: Handles routing of data packets between different networks. It determines the best path for data to travel from source to destination.

What it does: Manages logical addressing (IP addresses) and routing decisions across multiple networks.

Real-World Examples:

  • Internet Routing: Your request to visit a website finding the best path through internet routers
  • GPS Navigation: Finding the best route from your location to a destination
  • Corporate Networks: Data traveling between different office locations
  • VPN Connections: Routing encrypted traffic through secure tunnels

Common Protocols:

IP ICMP ARP OSPF BGP

Layer 2: Data Link Layer

Function: Handles communication between adjacent network nodes. It provides error detection and correction for the physical layer.

What it does: Manages frame formatting, MAC addresses, and controls access to the physical transmission medium.

Real-World Examples:

  • Ethernet Networks: Computers communicating on a local network switch
  • WiFi Connections: Your device connecting to a wireless access point
  • Bluetooth: Pairing devices and managing short-range communication
  • Network Switches: Forwarding data between devices on the same network

Common Protocols:

Ethernet WiFi (802.11) PPP Frame Relay ATM

Layer 1: Physical Layer

Function: Handles the physical transmission of raw binary data over communication channels. It defines electrical, mechanical, and procedural specifications.

What it does: Converts digital bits into electrical signals, radio waves, or light pulses for transmission over physical media.

Real-World Examples:

  • Ethernet Cables: Physical copper wires carrying electrical signals
  • Fiber Optic Cables: Light pulses traveling through glass fibers
  • Radio Waves: WiFi and cellular signals transmitted through air
  • USB Cables: Physical connection between devices

Common Technologies:

Copper Wire Fiber Optic Radio Frequency Infrared Bluetooth

Memory Trick to Remember the Layers

Here’s a popular mnemonic to remember the OSI layers from top to bottom:

“All People Seem To Need Data Processing”
  • Application
  • Presentation
  • Session
  • Transport
  • Network
  • Data Link
  • Physical

Interactive Demo: Data Flow Through OSI Layers

Watch how a simple web request travels through the OSI model:

๐Ÿ“ฑ Application Layer: User types “Hello World” in web browser
๐Ÿ”’ Presentation Layer: Encrypts data using HTTPS/TLS
๐Ÿ”— Session Layer: Establishes HTTP session with server
๐Ÿ“ฆ Transport Layer: TCP breaks data into packets, adds port numbers
๐Ÿ—บ Network Layer: Adds IP addresses for routing
๐Ÿ“ก Data Link Layer: Adds MAC addresses for local delivery
โšก Physical Layer: Converts to electrical/optical signals
๐Ÿ“ฅ Data received and processed in reverse order at destination

Real-World Application Examples

๐Ÿ“ง Email Communication

Application: Outlook/Gmail interface

Presentation: Text encoding, attachment compression

Session: SMTP session management

Transport: TCP ensures reliable delivery

Network: IP routing to mail server

Data Link: Ethernet frame to local router

Physical: Electrical signals over cable

๐ŸŽฅ Video Streaming

Application: Netflix/YouTube player

Presentation: Video compression (H.264/H.265)

Session: Streaming session management

Transport: UDP for real-time delivery

Network: IP routing with QoS

Data Link: WiFi 802.11 frames

Physical: Radio waves from router

๐Ÿ›’ Online Shopping

Application: Shopping cart interface

Presentation: HTTPS encryption for security

Session: Shopping session cookies

Transport: TCP for data integrity

Network: IP routing to e-commerce server

Data Link: Ethernet switching

Physical: Fiber optic connections

โ˜ Cloud Storage

Application: Google Drive/OneDrive

Presentation: File compression and encryption

Session: Authentication and sync sessions

Transport: TCP for file integrity

Network: IP routing to cloud servers

Data Link: Multiple link technologies

Physical: Various transmission media

OSI vs TCP/IP Model Comparison

OSI Layer OSI Function TCP/IP Layer Common Protocols
Application User interface and network services Application HTTP, HTTPS, FTP, SMTP, DNS
Presentation Data encryption and compression SSL/TLS, JPEG, MPEG, ASCII
Session Session management NetBIOS, RPC, SQL
Transport Reliable data transfer Transport TCP, UDP
Network Routing and logical addressing Internet IP, ICMP, ARP, OSPF
Data Link Error detection and MAC addressing Network Access Ethernet, WiFi, PPP
Physical Physical transmission of bits Copper, Fiber, Radio

Why is the OSI Model Important?

๐ŸŽฏ Benefits of Understanding the OSI Model:

  • Troubleshooting: When your internet isn’t working, you can systematically check each layer to identify the problem
  • Network Design: Architects use the OSI model to design robust network infrastructures
  • Protocol Development: New networking protocols are developed with OSI layers in mind
  • Education: Provides a standardized way to teach and learn networking concepts
  • Interoperability: Ensures different vendors’ equipment can work together
  • Security: Each layer can implement specific security measures

Common Troubleshooting Using OSI Layers

๐Ÿ”ง Practical Troubleshooting Approach:

Problem: Website won’t load

  1. Physical Layer: Check if network cables are connected, WiFi is on
  2. Data Link Layer: Verify network adapter is working, getting MAC address
  3. Network Layer: Check if you have an IP address, can ping router
  4. Transport Layer: Test if specific ports are accessible
  5. Session Layer: Check if authentication/sessions are working
  6. Presentation Layer: Verify if encryption/certificates are valid
  7. Application Layer: Test if the web browser or application is functioning

Conclusion

The OSI model serves as a fundamental framework for understanding network communication. While modern networking often uses the simplified TCP/IP model in practice, the OSI model remains invaluable for education, troubleshooting, and designing network solutions. Each layer has distinct responsibilities, and understanding these layers helps network professionals design better systems, troubleshoot problems more effectively, and ensure reliable communication between diverse systems.

Whether you’re browsing the web, sending emails, streaming videos, or working with cloud applications, all these activities rely on the principles outlined in the OSI model. The next time you click a link or send a message, remember the complex but elegant process happening behind the scenes across all seven layers!

๐Ÿš€ Next Steps for Learning:

  • Explore specific protocols at each layer in detail
  • Practice network troubleshooting using the OSI approach
  • Learn about network security at different OSI layers
  • Study how modern technologies like cloud computing map to OSI layers
  • Experiment with network analysis tools like Wireshark

The post OSI Model Explained: 7 Layers with Real-World Examples appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/osi-model-explained/feed/ 0 592
IP Address vs. MAC Address: Whatโ€™s the Difference? https://learnwithexamples.org/ip-address-vs-mac-address/ https://learnwithexamples.org/ip-address-vs-mac-address/#respond Wed, 16 Jul 2025 07:48:51 +0000 https://learnwithexamples.org/?p=484 IP Address vs. MAC Address: What’s the Difference? 🏠 The Postal System Analogy Imagine you’re sending a letter to a friend. You need two key pieces of information: where they…

The post IP Address vs. MAC Address: Whatโ€™s the Difference? appeared first on Learn With Examples.

]]>
IP Address vs. MAC Address: What’s the Difference?

๐Ÿ  The Postal System Analogy

Imagine you’re sending a letter to a friend. You need two key pieces of information: where they live (their home address) and who they are (their name on the mailbox). In networking, IP addresses work like home addresses – they tell us where to send data on the internet. MAC addresses work like unique ID tags – they identify the specific device, like a person’s name on their mailbox.

Understanding the Basics

In the world of computer networking, two types of addresses play crucial roles in ensuring data reaches its destination: IP addresses and MAC addresses. While both serve as identifiers, they operate at different levels of network communication and serve distinct purposes. Understanding the difference between these addressing systems is fundamental to grasping how modern networks function.

Think of network communication like a sophisticated postal system. Just as the postal service needs both a street address to know where to deliver mail and a recipient’s name to ensure it reaches the right person, computer networks use both IP and MAC addresses to route data efficiently and accurately.

๐Ÿ“ฌ Postal System vs Network Communication

Sender’s Address
(Source IP)
โ†’
Post Office
(Router)
โ†’
Recipient’s Address
(Destination IP)
โ†’
Mailbox Name
(MAC Address)

What is an IP Address?

An Internet Protocol (IP) address is a unique numerical identifier assigned to every device connected to a network that uses the Internet Protocol for communication. It serves as a logical address that can change based on the device’s location within the network topology.

IP addresses come in two main versions: IPv4 and IPv6. IPv4 addresses consist of four numbers separated by dots (like 192.168.1.1), while IPv6 addresses use a longer hexadecimal format to accommodate the growing number of internet-connected devices.

๐ŸŒ Interactive IP Address Demo

Your Device
Click a button to see IP examples

๐Ÿ  IP Address as Home Address

Just like your home address changes when you move to a new house, your device’s IP address changes when you connect to different networks. When you’re at home, your laptop might have the IP address 192.168.1.100. When you take it to a coffee shop, it might become 10.0.0.50. The device is the same, but its “network address” changes based on location.

Types of IP Addresses

Private IP Addresses: These are used within local networks and are not routable on the internet. Common private IP ranges include 192.168.x.x, 10.x.x.x, and 172.16.x.x to 172.31.x.x.

Public IP Addresses: These are globally unique addresses assigned by Internet Service Providers (ISPs) and are used to identify devices on the internet.

Common IP Address Examples:
Private: 192.168.1.1 (typical home router)
Private: 10.0.0.1 (common in corporate networks)
Public: 8.8.8.8 (Google’s DNS server)
Loopback: 127.0.0.1 (localhost – your own device)

What is a MAC Address?

A Media Access Control (MAC) address is a unique hardware identifier assigned to every network interface controller (NIC) during manufacturing. Unlike IP addresses, MAC addresses are permanent and cannot be changed under normal circumstances (though they can be spoofed through software).

MAC addresses consist of 12 hexadecimal characters, typically displayed in pairs separated by colons or hyphens (like 00:1A:2B:3C:4D:5E). The first half identifies the manufacturer, while the second half is a unique identifier for that specific device.

๐Ÿ”ง Interactive MAC Address Demo

Network Device
Click a button to explore MAC addresses

๐Ÿท MAC Address as Device ID

Think of a MAC address like a social security number or a serial number on an appliance. Just as your social security number stays the same regardless of where you live, your network card’s MAC address remains constant whether you’re at home, at work, or traveling. It’s permanently “burned” into the hardware during manufacturing.

MAC Address Structure

A MAC address is divided into two parts: the Organizationally Unique Identifier (OUI) and the device-specific identifier. The OUI (first 24 bits) identifies the manufacturer, while the remaining 24 bits provide a unique identifier for each device from that manufacturer.

MAC Address Breakdown:
Example: 00:1A:2B:3C:4D:5E
OUI: 00:1A:2B (identifies manufacturer)
Device ID: 3C:4D:5E (unique device identifier)

Key Differences: IP vs MAC Addresses

Aspect IP Address MAC Address
Purpose Logical addressing for network routing Physical identification of network hardware
Changeability Can change (dynamic/static assignment) Permanent (burned into hardware)
Scope Global (internet-wide routing) Local (within same network segment)
Format IPv4: 192.168.1.1
IPv6: 2001:db8::1
00:1A:2B:3C:4D:5E
Layer Network Layer (Layer 3) Data Link Layer (Layer 2)
Assignment DHCP server or manual configuration Manufacturer during production

How They Work Together

IP and MAC addresses work in tandem to ensure successful data transmission. When you send data across a network, your device uses IP addresses to determine the destination, but it needs MAC addresses to physically deliver the data packets within each network segment.

๐Ÿ“ก Network Communication Layers

Application Layer – Your Email/Web Browser
Network Layer – IP Address Routing
Data Link Layer – MAC Address Delivery
Physical Layer – Electrical Signals

๐Ÿ”„ Address Resolution Protocol (ARP) Demo

ARP (Address Resolution Protocol) translates IP addresses to MAC addresses within a local network.

Click “Show ARP Process” to see how it works!

Real-World Examples and Applications

Example 1: Home Network

When you connect your smartphone to your home Wi-Fi, your router assigns it an IP address (like 192.168.1.100) through DHCP. However, your phone’s Wi-Fi adapter has a permanent MAC address (like 00:1A:2B:3C:4D:5E) that identifies it uniquely on the local network.

๐Ÿ  Home Network Scenario

Smartphone
IP: 192.168.1.100
MAC: 00:1A:2B:3C:4D:5E
Laptop
IP: 192.168.1.101
MAC: 00:1A:2B:3C:4D:5F
Router
IP: 192.168.1.1
MAC: 00:1A:2B:3C:4D:60

Example 2: Corporate Network

In a large office building, hundreds of devices might share the same network infrastructure. Each device has a unique MAC address, but they all receive IP addresses from the same corporate IP range (like 10.0.0.x). The MAC addresses help switches deliver data to the correct physical port, while IP addresses handle routing between different network segments.

Example 3: Internet Communication

When you visit a website, your computer uses IP addresses to route packets across the internet. However, at each network hop, routers use MAC addresses to forward packets to the next router in the path. The MAC addresses change at each hop, but the IP addresses remain the same throughout the journey.

๐Ÿ’ก Did You Know?

Every time a packet travels through a router, the MAC addresses in the packet header are replaced with new ones for the next network segment, but the IP addresses remain unchanged. This is why IP addresses are called “logical” addresses (they stay the same end-to-end) while MAC addresses are “physical” addresses (they change at each network hop).

Security Implications

Both IP and MAC addresses have important security implications. IP addresses can be used to track general location and network activity, while MAC addresses can be used for device fingerprinting and tracking within local networks.

โš  Privacy Considerations

MAC Address Privacy: Since MAC addresses are unique and permanent, they can be used to track devices across different networks. Modern operating systems now use MAC address randomization to enhance privacy.

IP Address Privacy: Your public IP address can reveal your approximate location and ISP. VPNs and proxy servers can help mask your real IP address.

Troubleshooting with IP and MAC Addresses

Network administrators regularly use both IP and MAC addresses for troubleshooting and network management. Understanding how to work with both types of addresses is essential for diagnosing connectivity issues.

Common Network Commands:
Windows: ipconfig /all (shows both IP and MAC)
Mac/Linux: ifconfig (shows both IP and MAC)
Windows: arp -a (shows ARP table)
Ping: ping 192.168.1.1 (tests IP connectivity)

Common Troubleshooting Scenarios

Scenario 1: Device Can’t Connect to Network
Check if the device has a valid IP address. If it shows 169.254.x.x (Windows) or similar, the device couldn’t obtain an IP address from the DHCP server.

Scenario 2: Duplicate IP Address
Two devices accidentally configured with the same IP address will cause conflicts. The MAC addresses help identify which physical devices are involved.

Scenario 3: MAC Address Filtering
Some routers use MAC address filtering for security. If a device can’t connect, check if its MAC address is on the allowed list.

Future Considerations

As technology evolves, both IP and MAC addressing systems continue to adapt. IPv6 adoption is growing to address the shortage of IPv4 addresses, while MAC address randomization is becoming more common to protect user privacy.

The Internet of Things (IoT) is creating billions of new connected devices, each requiring both IP and MAC addresses. Understanding these fundamental networking concepts becomes increasingly important as our world becomes more connected.

๐Ÿ”ฎ Looking Forward

With IPv6, we have enough addresses for every grain of sand on Earth to have its own IP address. MAC addresses are also evolving, with new standards like EUI-64 providing more addresses for the growing number of network devices.

Conclusion

IP and MAC addresses serve complementary but distinct roles in network communication. IP addresses provide logical addressing for routing data across networks, much like street addresses guide mail delivery. MAC addresses provide physical identification of network hardware, similar to unique serial numbers on devices.

Understanding the difference between these addressing systems is crucial for anyone working with networks, from basic home networking to complex enterprise infrastructure. While IP addresses handle the “where” of network communication, MAC addresses handle the “what” – together, they ensure that data reaches its intended destination reliably and efficiently.

As networking technology continues to evolve, these fundamental concepts remain essential building blocks for understanding how modern networks operate. Whether you’re troubleshooting connectivity issues, designing network security policies, or simply curious about how your devices communicate, the relationship between IP and MAC addresses forms the foundation of network communication.

๐ŸŽฏ Final Analogy

Think of network communication like a sophisticated delivery system: IP addresses are like GPS coordinates that guide packages across the globe, while MAC addresses are like the specific delivery truck that actually carries the package to your doorstep. Both are necessary, both serve different purposes, and both work together to ensure successful delivery.

Also check: What is DNS? Complete Guide with Examples

The post IP Address vs. MAC Address: Whatโ€™s the Difference? appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/ip-address-vs-mac-address/feed/ 0 484
What is DNS? Complete Guide with Examples https://learnwithexamples.org/what-is-dns/ https://learnwithexamples.org/what-is-dns/#respond Tue, 01 Jul 2025 09:27:46 +0000 https://learnwithexamples.org/?p=476 What is DNS? Explained with Website Lookup Example Learn how typing www.google.com translates into an IP address through DNS lookup What is DNS? The Domain Name System (DNS) is like…

The post What is DNS? Complete Guide with Examples appeared first on Learn With Examples.

]]>
What is DNS? Explained with Website Lookup Example

Learn how typing www.google.com translates into an IP address through DNS lookup

What is DNS?

The Domain Name System (DNS) is like the phonebook of the internet. Just as you use a phonebook to look up someone’s phone number by their name, DNS translates human-readable domain names (like www.google.com) into IP addresses (like 142.250.191.78) that computers use to communicate with each other.

Think of it this way: Imagine trying to remember the phone numbers of all your contacts instead of their names. That’s what browsing the internet would be like without DNS – you’d have to memorize IP addresses for every website you want to visit!

Every device connected to the internet has a unique IP address, which is essentially its “home address” on the web. When you type a domain name in your browser, DNS servers work behind the scenes to find the correct IP address and connect you to the right website.

How DNS Works: The Complete Process

When you type www.google.com in your browser and press Enter, here’s what happens behind the scenes:

1 Your computer checks its cache: First, your computer looks in its local DNS cache to see if it recently looked up this domain. If found, it uses the cached IP address.
2 Query to Recursive Resolver: If not cached, your computer sends a DNS query to a recursive resolver (usually provided by your ISP or services like Google DNS 8.8.8.8).
3 Root Server Query: The recursive resolver queries one of 13 root DNS servers worldwide. The root server responds with the address of the appropriate Top-Level Domain (TLD) server.
4 TLD Server Query: The resolver queries the .com TLD server (since google.com ends in .com). The TLD server responds with the authoritative name server for google.com.
5 Authoritative Server Query: Finally, the resolver queries Google’s authoritative name server, which returns the IP address for www.google.com.
6 Response Back to You: The resolver sends the IP address back to your computer, which can now connect directly to Google’s servers.

DNS Hierarchy Structure

DNS follows a hierarchical structure, much like a tree with branches. Let’s break down the components using www.google.com as an example:

Root Level

. (dot)

โ†“

Top-Level Domain

.com

โ†“

Second-Level Domain

google

โ†“

Subdomain

www

Root Domain

Represented by a dot (.)

Managed by 13 root servers globally

โ†’

TLD (.com)

Top-Level Domain

Managed by registry operators

โ†’

Domain (google)

Second-Level Domain

Owned by organizations

โ†’

Subdomain (www)

Third-Level Domain

Configured by domain owner

Interactive DNS Lookup Simulator

Try our interactive DNS lookup tool to see how domain name resolution works in real-time:

DNS Lookup Simulation


Step 1: Checking local DNS cache…
Looking for cached DNS records on your computer
Step 2: Contacting recursive resolver…
Sending query to DNS resolver (e.g., 8.8.8.8)
Step 3: Querying root DNS server…
Root server responds with TLD server address
Step 4: Querying TLD server (.com)…
TLD server provides authoritative name server
Step 5: Querying authoritative name server…
Getting the actual IP address from domain owner’s server
Step 6: DNS resolution complete!
IP address returned to your browser

DNS Lookup Result:

Domain:

IP Address:

Time Taken:

Record Type: A Record

Real-World Example: www.google.com Lookup

Let’s trace through a real DNS lookup for www.google.com step by step:

Step 1: Local Cache Check

Your computer first checks its local DNS cache. On Windows, you can view this cache using the command:

ipconfig /displaydns

If www.google.com was recently visited, the IP address might be cached here for quick access.

Step 2: Recursive Resolver Query

Your computer sends a DNS query to your configured DNS resolver. This might be:

  • Google DNS: 8.8.8.8 or 8.8.4.4
  • Cloudflare DNS: 1.1.1.1
  • Your ISP’s DNS: Automatically configured

Step 3: Root Server Response

The recursive resolver queries one of the 13 root DNS servers. The root server responds with:

com. 172800 IN NS a.gtld-servers.net. com. 172800 IN NS b.gtld-servers.net.

This tells the resolver which servers handle .com domains.

Step 4: TLD Server Response

The resolver queries the .com TLD server, which responds with Google’s authoritative name servers:

google.com. 172800 IN NS ns1.google.com. google.com. 172800 IN NS ns2.google.com. google.com. 172800 IN NS ns3.google.com. google.com. 172800 IN NS ns4.google.com.

Step 5: Authoritative Server Response

Finally, querying Google’s authoritative name server returns:

www.google.com. 300 IN A 142.250.191.78

This is the actual IP address your browser will use to connect to Google’s servers!

Types of DNS Records

DNS isn’t just about converting domain names to IP addresses. There are several types of DNS records, each serving different purposes:

Common DNS Record Types

A Record Address Record: Maps a domain name to an IPv4 address (like 192.168.1.1). This is the most common type of DNS record.
AAAA Record IPv6 Address Record: Maps a domain name to an IPv6 address (like 2001:db8::1). Used for the newer IPv6 protocol.
CNAME Canonical Name: Creates an alias for a domain name. For example, www.example.com might be a CNAME pointing to example.com.
MX Record Mail Exchange: Specifies the mail servers responsible for accepting email for a domain.
TXT Record Text Record: Stores arbitrary text data, often used for email verification, domain verification, and security policies.
NS Record Name Server: Specifies which DNS servers are authoritative for a domain.

DNS Caching and TTL

DNS caching is crucial for internet performance. Without caching, every web request would require a full DNS lookup, making the internet unbearably slow.

How DNS Caching Works

DNS records come with a Time To Live (TTL) value, which tells DNS resolvers how long they can cache the record before checking for updates. Here’s how caching works at different levels:

Browser Cache: Your browser caches DNS lookups for a short period (usually 1 minute) to speed up page loading.
Operating System Cache: Your OS maintains its own DNS cache, typically lasting several minutes to hours.
Resolver Cache: DNS resolvers (like your ISP’s or Google’s) cache records based on their TTL values, which can range from minutes to days.

TTL Example

When you see a DNS record like this:

www.google.com. 300 IN A 142.250.191.78

The “300” is the TTL in seconds (5 minutes). This means DNS resolvers can cache this record for up to 5 minutes before checking for updates.

DNS Security and Privacy

Traditional DNS queries are sent in plain text, which raises privacy and security concerns. Several technologies have been developed to address these issues:

DNS Security Technologies

DNSSEC (DNS Security Extensions): Adds cryptographic signatures to DNS records to ensure they haven’t been tampered with during transmission.
DNS over HTTPS (DoH): Encrypts DNS queries using HTTPS, making them indistinguishable from regular web traffic.
DNS over TLS (DoT): Encrypts DNS queries using TLS encryption on a dedicated port (853).

Common DNS Security Threats

Understanding DNS security is important because DNS can be a target for various attacks:

  • DNS Spoofing: Attackers provide false DNS responses to redirect users to malicious websites
  • DNS Cache Poisoning: Corrupting DNS cache with false information
  • DNS Hijacking: Redirecting DNS queries to attacker-controlled servers
  • DNS Tunneling: Using DNS queries to exfiltrate data or establish covert communication

Troubleshooting DNS Issues

DNS problems can prevent you from accessing websites. Here are common issues and how to diagnose them:

Common DNS Problems

1 “Server not found” errors: Often indicates DNS resolution failures. Try using different DNS servers like 8.8.8.8 or 1.1.1.1.
2 Slow website loading: Might be caused by slow DNS resolution. Check your DNS server response times.
3 Inconsistent website access: Could indicate DNS cache issues or DNS server problems.

DNS Troubleshooting Tools

Here are some useful commands for diagnosing DNS issues:

# Windows Commands nslookup www.google.com ipconfig /flushdns ipconfig /displaydns # Mac/Linux Commands dig www.google.com host www.google.com sudo dscacheutil -flushcache # Mac sudo systemctl restart systemd-resolved # Linux

The Future of DNS

DNS technology continues to evolve to meet the demands of a growing internet. Here are some emerging trends and technologies:

Emerging DNS Technologies

DNS over QUIC (DoQ): A newer protocol that promises even faster and more secure DNS resolution by using the QUIC transport protocol.

Encrypted Client Hello (ECH): Works alongside DNS to provide better privacy by encrypting the initial connection handshake.

DNS-based Authentication of Named Entities (DANE): Uses DNS to store cryptographic certificates, improving security for email and web connections.

Performance Improvements

Modern DNS resolver services like Cloudflare (1.1.1.1) and Google (8.8.8.8) use anycast routing and advanced caching techniques to provide faster DNS resolution times, often responding in under 20 milliseconds.

Conclusion

DNS is truly the unsung hero of the internet. Every time you visit a website, send an email, or use any internet service, DNS is working behind the scenes to translate human-readable names into the IP addresses that computers understand.

Understanding how DNS works helps you:

  • Troubleshoot internet connectivity issues
  • Improve your browsing speed by choosing better DNS servers
  • Understand internet security and privacy concerns
  • Appreciate the complex infrastructure that makes the modern internet possible

The next time you type www.google.com and instantly see Google’s homepage, remember the incredible journey that domain name took through the DNS system – from your computer to root servers, TLD servers, and authoritative name servers – all in the blink of an eye!

Key Takeaway: DNS converts human-readable domain names (like www.google.com) into IP addresses (like 142.250.191.78) through a hierarchical system of DNS servers, enabling the user-friendly internet experience we all enjoy today.

Also check: Learn about Networking Basics

The post What is DNS? Complete Guide with Examples appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-is-dns/feed/ 0 476
Let’s Learn about Networking Basics https://learnwithexamples.org/lets-learn-networking-basics/ https://learnwithexamples.org/lets-learn-networking-basics/#respond Tue, 30 Jan 2024 09:43:32 +0000 https://learnwithexamples.org/?p=37 Have you ever wondered how your phone chats with your laptop, shares pictures with grandma in another city, or streams that hilarious cat video? It’s all thanks to magic, right?…

The post Let’s Learn about Networking Basics appeared first on Learn With Examples.

]]>
Have you ever wondered how your phone chats with your laptop, shares pictures with grandma in another city, or streams that hilarious cat video? It’s all thanks to magic, right? Well, not quite! It’s thanks to something called networking, and learning its basics is like learning a secret language that lets you understand how the digital world talks.

But networking can sound scary, like a complicated maze of wires and jargon. Don’t worry, though! Think of your own home as a network, and suddenly, it’s not so intimidating anymore. Let’s explore!

Chapter 1: The Tale of Connected Devices

Once upon a time, in the magical land of the internet, there lived a multitude of devices – laptops, smartphones, tablets, and more. They yearned to communicate with each other, share information, and work together harmoniously. But how could they achieve this seamless connectivity?

Enter the protagonist, the Network. A network is like a bustling city where devices dwell, sharing information through pathways called data highways. Think of it as the intricate roads that connect houses in a neighborhood. Just as these roads facilitate the movement of people, the network enables the flow of data between devices.

Chapter 2: The Language of Networking – Protocols

In our digital city, devices communicate using a common language known as protocols. Imagine if every house had its own secret language; communication would be chaos! Similarly, devices speak in protocols to ensure a smooth exchange of information.

The most famous protocol family is the TCP/IP (Transmission Control Protocol/Internet Protocol). TCP ensures that data reaches its destination reliably, like a trustworthy postal service, while IP addresses act as the unique identifiers for each device in the network.

Also check: Letโ€™s Learn Statistics

Chapter 3: Meet the Gatekeepers – Routers and Switches

In our digital city, there are two key guardians ensuring order and efficiency – routers and switches.

Routers are like traffic controllers directing data between different networks. Imagine them as decision-makers at intersections, deciding which path data should take to reach its destination. They connect your home network to the broader internet, making sure data finds its way in and out.

Switches, on the other hand, operate within a local network, like the inner roads of our city. They forward data only to the specific device it’s intended for, preventing unnecessary traffic jams and ensuring a smooth flow of information within the network.

Also check: Magic of Probability

Chapter 4: The Great Divide – LAN and WAN

In our digital city, networks can be categorized into two types: Local Area Network (LAN) and Wide Area Network (WAN).

A LAN is like a small neighborhood where devices are closely connected, such as your home network. Devices within a LAN can communicate directly with each other, just like neighbors sharing a backyard fence.

Meanwhile, a WAN spans larger distances, connecting multiple LANs. The internet itself is a colossal WAN, bridging gaps between cities, countries, and continents. It’s the grand highway allowing data to travel globally.

Chapter 5: The Mystery of DNS

Every device in our digital city has a unique identifier – its IP address. But humans find it more convenient to remember names than numbers. That’s where the Domain Name System (DNS) comes into play.

DNS is like a phonebook for the internet, translating human-readable domain names (like www.example.com) into IP addresses. Instead of remembering a string of numbers, we simply type the domain name, and DNS magically directs us to the correct IP address.

Also check: Let’s Learn Algorithms

Chapter 6: The Security Guards – Firewalls

In our digital city, security is paramount. Imagine if anyone could enter your home uninvited! Firewalls act as vigilant security guards, protecting networks from unauthorized access and potential cyber threats.

Firewalls monitor incoming and outgoing data, permitting or blocking traffic based on predefined security rules. They ensure that only the right data gets through, safeguarding the integrity of our digital community.

Chapter 7: Wireless Wonders – Wi-Fi

Picture our digital city evolving into a smart city where devices communicate without physical cables. This wireless marvel is made possible by Wi-Fi technology.

Wi-Fi is like the invisible magic that allows devices to connect without being tethered by cables. It’s akin to the air we breathe, enabling seamless communication between devices within the network.

Conclusion: Navigating the Digital Landscape

And so, our journey through the enchanting world of Networking Basics comes to an end. We’ve explored the bustling city of networks, met its inhabitants, and discovered the protocols, routers, switches, LANs, WANs, DNS, firewalls, and Wi-Fi that make it all possible.

As you embark on your own adventures in the digital landscape, remember that understanding networking basics is the key to unlocking the full potential of your devices. So, whether you’re a curious user or an aspiring IT enthusiast, the knowledge gained in this journey will serve as your trusty map through the vast realm of computer networking. Happy exploring!

The post Let’s Learn about Networking Basics appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/lets-learn-networking-basics/feed/ 0 37