Routers, switches and basic network security
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your interviewer says "my college blocks a website. How?" and expects hubs, switches, routers, firewalls and proxies to come out in one clear answer. The test is whether you can tell each device apart by the layer and the address it reads.
Hub vs switch vs router vs gateway
A switch is a layer 2 device that learns which MAC address is on which port and sends each frame only to the right port. A hub just repeats a signal to every port, and a router (layer 3) connects different networks by IP address.
Two examples: a hub flooding against a switch learning MAC addresses, and a router choosing the longest matching prefix.
Example 1 · Hub vs switch: flooding and MAC learning
mac_table = {}
def switch_frame(src_mac, in_port, dst_mac): mac_table[src_mac] = in_port # learn where the sender lives out_port = mac_table.get(dst_mac) if out_port is None: return f"flood to all ports except {in_port}" return f"send only to port {out_port}"
print("Hub: A -> C repeated to ports 2, 3, 4 (always)")print("Switch:")print(" A(port 1) -> C:", switch_frame("AA", 1, "CC"))print(" C(port 3) -> A:", switch_frame("CC", 3, "AA"))print(" A(port 1) -> C:", switch_frame("AA", 1, "CC"))print(" B(port 2) -> D:", switch_frame("BB", 2, "DD"))print("MAC table:", dict(sorted(mac_table.items())))Hub: A -> C repeated to ports 2, 3, 4 (always)
Switch:
A(port 1) -> C: flood to all ports except 1
C(port 3) -> A: send only to port 1
A(port 1) -> C: send only to port 3
B(port 2) -> D: flood to all ports except 2
MAC table: {'AA': 1, 'BB': 2, 'CC': 3}What this code does
- The switch learns from the source MAC of every frame. While it does not know the destination it floods like a hub; once it learns, it sends to one port only.
- A hub never learns, so every device sees every frame. That wastes bandwidth and makes sniffing easy, which is why switches replaced hubs.
Example 2 · A router choosing the longest matching prefix
import ipaddress
table = [ ("10.0.0.0/8", "campus core"), ("10.20.0.0/16", "hostel block"), ("10.20.5.0/24", "hostel B wing"), ("0.0.0.0/0", "ISP (default route)"),]routes = [(ipaddress.ip_network(net), hop) for net, hop in table]
for ip in ["10.20.5.9", "10.20.7.1", "10.3.3.3", "142.250.1.1"]: address = ipaddress.ip_address(ip) matching = [(net, hop) for net, hop in routes if address in net] net, hop = max(matching, key=lambda route: route[0].prefixlen) # longest prefix wins print(f"{ip:<12} -> /{net.prefixlen:<2} {hop}")10.20.5.9 -> /24 hostel B wing 10.20.7.1 -> /16 hostel block 10.3.3.3 -> /8 campus core 142.250.1.1 -> /0 ISP (default route)
What this code does
- Several routes can match one address. The router uses the longest prefix match: the most specific route wins, so 10.20.5.9 goes to the /24 even though the /16 and /8 also match.
- The 0.0.0.0/0 default route matches everything and is used only when nothing more specific does, which is how traffic reaches the internet.
A hub (layer 1) copies every incoming signal to all other ports, so all devices share one collision domain. A router (layer 3) forwards packets by IP address using a routing table. A gateway is the device that connects your network to another network; for a home or hostel, the default gateway is usually the Wi-Fi router.
Compare them:
- Hub: no learning, one collision domain, half duplex. Obsolete today.
- Switch: MAC address table, each port its own collision domain, full duplex; one broadcast domain (per VLAN).
- Router: routing table, separates broadcast domains, often does NAT, DHCP and firewalling at home.
- Others to name: repeater (L1, boosts signal), bridge (L2, joins two segments), access point (Wi-Fi to wired), modem (converts signals on the ISP line).
LAN, WAN and VLAN basics
A VLAN (virtual LAN) splits one physical switch into several separate layer 2 networks, so ports on the same switch can be kept apart. Each VLAN has an ID and is its own broadcast domain.
The example puts the ports of one switch into VLANs and shows which ports can reach each other directly.
Example 3 · VLANs on one switch
port_vlan = {1: 10, 2: 10, 3: 20, 4: 20, 5: 30}names = {10: "Students", 20: "Staff", 30: "Exam server"}
from_port = 1vlan = port_vlan[from_port]reach = [port for port, v in port_vlan.items() if v == vlan and port != from_port]print(f"Broadcast from port {from_port} (VLAN {vlan} {names[vlan]}) reaches ports:", *reach)
same = port_vlan[1] == port_vlan[5]print(f"Port 1 to port 5 ({names[30]}):", "same VLAN, switched" if same else "different VLAN, needs router/firewall")Broadcast from port 1 (VLAN 10 Students) reaches ports: 2 Port 1 to port 5 (Exam server): different VLAN, needs router/firewall
What this code does
- A broadcast from a student port reaches only the other port in VLAN 10. Staff and exam server ports never see it, even on the same switch.
- Students reaching the exam server must go through a router or firewall, where rules can block them. VLANs separate traffic; the rules between them give the security.
A LAN (local area network) covers one building or campus, such as a college lab. A WAN (wide area network) connects distant sites, such as all branches of a bank; the internet is the largest WAN. A MAN covers a city. Ports for students, staff and exam servers can be on different VLANs even on the same switch, so their broadcasts stay apart and a router or firewall controls traffic between them.
VLAN facts:
- Each VLAN has an ID (1 to 4094) and is its own broadcast domain, usually its own IP subnet.
- A trunk link carries many VLANs between switches, tagging each frame with its VLAN ID (802.1Q).
- Traffic between VLANs needs a router or a layer 3 switch.
Firewalls, VPNs and proxies
A firewall allows or blocks traffic by rules. Rules are checked top to bottom and the first match wins, usually ending with "deny everything else". A stateful firewall also remembers connections, so replies to your requests get in.
The example applies ordered firewall rules to packets, so you can see that the first matching rule decides.
Example 4 · Firewall rules: first match wins
from typing import NamedTuple
class Rule(NamedTuple): action: str src_prefix: str port: int # 0 means any port
def decide(rules, src_ip, port): for number, rule in enumerate(rules, start=1): src_ok = rule.src_prefix == "*" or src_ip.startswith(rule.src_prefix) port_ok = rule.port in (0, port) if src_ok and port_ok: return f"{rule.action} (rule {number})" return "DENY (no rule)"
rules = [Rule("DENY", "45.33.", 0), Rule("ALLOW", "*", 443), Rule("ALLOW", "10.20.", 22), Rule("DENY", "*", 0)]packets = [("103.5.6.7", 443), ("45.33.1.1", 443), ("10.20.5.9", 22), ("103.5.6.7", 22), ("10.20.5.9", 3306)]for src_ip, port in packets: print(f"{src_ip:<10} port {port:<4} -> {decide(rules, src_ip, port)}")103.5.6.7 port 443 -> ALLOW (rule 2) 45.33.1.1 port 443 -> DENY (rule 1) 10.20.5.9 port 22 -> ALLOW (rule 3) 103.5.6.7 port 22 -> DENY (rule 4) 10.20.5.9 port 3306 -> DENY (rule 4)
What this code does
- Rules are checked top to bottom and the first match decides. The blocked range 45.33.x is denied even on port 443, because its DENY rule comes before the ALLOW for 443.
- SSH is allowed only from the campus range 10.20.x, and the last rule denies everything else, including the database port 3306. This is a simplified prefix check, not real CIDR matching.
A VPN (virtual private network) builds an encrypted tunnel from your device to a VPN server, so your traffic looks like it comes from inside the company network. A proxy makes requests on behalf of clients: a forward proxy sits in front of users (for example a college web filter), and a reverse proxy sits in front of servers (for example Nginx doing load balancing and TLS).
Tell them apart:
- Firewall: decides allow or deny. VPN: encrypts and tunnels. Proxy: forwards requests for others.
- A VPN encrypts traffic between you and the VPN server only, not all the way to the website.
- Network firewalls protect a whole network; host firewalls (such as Windows Defender Firewall) protect one machine.
Common attacks: DoS, man-in-the-middle and phishing
A DDoS attack floods a server with requests from thousands of infected machines (a botnet) at once, so real users cannot get through and blocking one address does not stop it. A DoS (denial of service) attack does the same from one source.
The example flags a suspicious link with a fake bank domain and a request flood from one IP address.
Example 5 · Spotting phishing links and request floods
from collections import Counterfrom urllib.parse import urlsplit
def link_verdict(url, real_domain): host = urlsplit(url).hostname ok = host == real_domain or host.endswith("." + real_domain) return ("looks genuine " if ok else "SUSPICIOUS ") + host
links = [ "https://www.mybank.in/login", "https://mybank.in.secure-kyc.xyz/login", "https://www-mybank.in/update", "https://netbanking.mybank.in/otp",]for link in links: print(link_verdict(link, "mybank.in"))
per_ip = Counter()limit = 3for ip in ["1.1.1.1", "2.2.2.2", "1.1.1.1", "1.1.1.1", "1.1.1.1", "3.3.3.3", "1.1.1.1"]: per_ip[ip] += 1 if per_ip[ip] == limit + 1: print(f"rate limit: blocking {ip} after {limit} requests")looks genuine www.mybank.in SUSPICIOUS mybank.in.secure-kyc.xyz SUSPICIOUS www-mybank.in looks genuine netbanking.mybank.in rate limit: blocking 1.1.1.1 after 3 requests
What this code does
- What counts is the real host, read from right to left.
mybank.in.secure-kyc.xyzbelongs tosecure-kyc.xyz, andwww-mybank.inis a different domain altogether: both are classic phishing tricks. - The second part counts requests per IP in a time window and blocks one that goes over the limit: the idea behind rate limiting against simple DoS. A DDoS from thousands of IPs needs bigger, upstream protection.
Defences include rate limiting, CDNs and DDoS protection services that absorb traffic. In a man-in-the-middle (MITM) attack, the attacker secretly relays and may change traffic between two parties, for example through a fake Wi-Fi hotspot or ARP spoofing; HTTPS with certificate checks is the main defence. Phishing tricks people with fake emails, SMS or sites that look real, to steal passwords or OTPs. Check the real domain, never share OTPs and use multi-factor authentication.
Also know:
- Spoofing: faking an IP, MAC or email sender address.
- Sniffing: reading traffic on a network; encryption makes it useless.
- Brute force: trying many passwords; stop it with lockouts, rate limits and strong passwords.
- Malware and ransomware: harmful software, often delivered by phishing.
Find the bug
Name the right attack or defence
Each list has one wrong line. Tap it, then check the fix.
A candidate matches cases to attacks.
Round 1 of 2Answering device and security questions
For "difference between" questions, use one line per item that names the layer, the address it reads and what it does. For security questions, name the attack, how it works in one sentence, and one or two defences.
Q: Difference between a hub, a switch and a router?A: A hub works at layer 1 and repeats every signal to all ports, so everyone shares the bandwidth and sees all traffic. A switch works at layer 2: it learns MAC addresses and sends each frame only to the port where the destination is. A router works at layer 3: it connects different networks and forwards packets by IP address using its routing table. At home one box usually does all of this plus Wi-Fi, DHCP and NAT.Use examples from your own life: the hostel Wi-Fi router (router, switch, access point, DHCP and NAT in one box), a college firewall that blocks some sites, a UPI phishing SMS.
Order of execution
Build a firewall answer
An interviewer asks "What is a firewall?" Put the parts of a strong answer in order.
Next step
Check your understanding
12 quick questions