CN / zero → interview
Computer Networks · interview prep · Hinglish

Network samajhna matlab ek packet ki poori journey samajhna.

Ye page tumhe zero se shuru karke interview-ready tak le jayega. Har topic mein: pehle intuition (analogy se), phir proper definition, phir diagram/example, phir interview mein kya poochhte hain, aur last mein practice questions with full solution.

Rule: har section ke Q boxes ko pehle khud solve karo, phir solution kholo. Padhna easy hai, solve karna asli test hai.

L5 Application
L4 Transport
L3 Network
L2 Link
L1 Physical
00 · orientation

Ye page kaise padhna hai

Pehle 5 minute isko padho, warna 25 sections dekh ke ghabra jaoge.

08162431

Computer Networks ka syllabus bada lagta hai, lekin asal mein bas ek hi kahani hai: tumhare browser se ek request nikli, aur wo Google ke server tak pahunchi aur wapas aayi. Bas isi journey ko 5 layers mein tod diya gaya hai. Har layer ka ek kaam hai, aur har layer ke apne protocols hain.

Mental model — isko dimaag mein fix kar lo

Ek courier company socho. Tum ek letter likhte ho (Application layer). Use ek envelope mein daalte ho jispe "yeh letter number 3 of 10 hai, receipt bhejna" likha hai (Transport layer). Us envelope ko ek bade parcel mein daalte ho jispe pura address likha hai (Network layer). Parcel truck mein jaata hai, har city ke bich mein alag truck (Link layer), aur road/highway hi Physical layer hai.

Padhne ka order

  1. Section 01–03 must hai. Basics + layering + delay formulas. Inke bina baaki sab hawa mein hai.
  2. Section 04, 05, 09, 12, 20 — ye 5 sections interview mein sabse zyada poochhe jaate hain (HTTP, DNS, TCP, subnetting, ARP). Agar time kam hai to yahin se start karo.
  3. Baaki sections depth ke liye — college exam / on-campus test / SDE-1 deep rounds mein kaam aate hain.
  4. Last mein Section 22 (google.com walk-through) padho — wo saare topics ko ek dhaage mein baandh deta hai. Wo hi sabse common interview question hai.

Badges ka matlab

★★★ asked a lot — har doosre interview mein ★★ common — deep rounds mein
Notes banane ka tareeka

Har section ke end mein "Interview mein kya bolna hai" wala box hai — wahi tumhara notes page hai. Pura section copy mat karo, sirf wo box + formula boxes + tables utaaro. Ek A4 sheet per section, bas.

Ctrl+P dabaoge to print-friendly version nikal jayega (sidebar aur buttons hat jayenge). Solutions jo khule honge wahi print honge — to pehle "⊕ all" dabao.

01 · foundations

Network kya hai, Internet kaise bana hai

Hosts, links, routers, ISPs, aur switching ke do tareeke.

08162431

1.1 Sabse pehle: network ki definition

Definition

Ek computer network = do ya zyada computing devices jo communication links se jude hain aur aapas mein data exchange kar sakte hain, ek common set of rules (protocol) follow karte hue.

Internet ko do tareeke se dekha jaata hai — ye distinction interview mein "What is the Internet?" ka perfect answer banata hai:

Nuts-and-bolts view (hardware)

Internet = billions of connected devices (hosts/end systems) + communication links (fiber, copper, radio) + packet switches (routers, link-layer switches). Ye "network of networks" hai — chhote ISPs bade ISPs se jude hue.

Service view (software)

Internet = ek infrastructure jo distributed applications ko services deta hai (web, email, streaming, gaming), aur programs ko ek API deta hai (sockets) jisse wo data bhej-le sakein.

Basic vocabulary — inko confuse mat karna

TermMatlabExample
Host / End systemNetwork ke "kinare" pe baithi device jo application run karti haiLaptop, phone, server, smart TV
ClientRequest bhejne wala hostChrome browser
ServerRequest ka jawab dene wala, always-on hostGoogle ka web server
LinkDo devices ke beech ka physical raastaFiber cable, WiFi radio
RouterNetwork layer (L3) device — IP address dekh ke packet forward karta hai, networks ko jodta haiGhar ka "WiFi router" (actually router+switch+AP)
SwitchLink layer (L2) device — MAC address dekh ke frame forward karta hai, ek hi LAN ke andarOffice ka network switch
ISPInternet Service Provider — tumhe Internet se jodta haiJio, Airtel
ProtocolMessage format + order + action ke rulesHTTP, TCP, IP
Protocol ki formal definition (ye ratt lo, interview mein poochte hain)

A protocol defines the format and the order of messages exchanged between two or more communicating entities, as well as the actions taken on the transmission and/or receipt of a message.

Yaani teen cheezein: kaise dikhega message, kis order mein aayega, aur milne pe kya karna hai.

1.2 Network ka structure: edge, core, access

   NETWORK EDGE              ACCESS NETWORK            NETWORK CORE
   (hosts: clients,      →      (last mile: DSL,      →      (mesh of routers,
    servers, IoT)                cable, fiber, LTE,           ISP backbones,
                                 WiFi, Ethernet)              IXPs, peering)
    
  • Network edge — applications yahin chalti hain (tumhara laptop, data center servers).
  • Access network — edge ko core se jodne wali "last mile" link. Yahan par bandwidth shared hai ya dedicated ye important hai: cable Internet mein neighbourhood share karta hai (isliye shaam ko slow), DSL/fiber dedicated hota hai.
  • Network core — interconnected routers ka mesh jo packets ko source se destination tak pahunchata hai. Core ke do main kaam: forwarding (local: input port se sahi output port pe bhejo) aur routing (global: pura raasta decide karo).
Forwarding vs Routing — favourite interview trap

Forwarding = local action, ek router ke andar, microseconds mein: incoming packet ko dekh ke forwarding table se sahi output link chuno. (Data plane)

Routing = global process: saare routers milke decide karte hain ki source→destination ka best path kya hai, aur uske hisaab se forwarding tables banti hain. (Control plane)

One-liner: "Routing decides the route, forwarding moves the packet." Analogy: routing = Google Maps se route plan karna, forwarding = chauraahe pe sahi turn lena.

1.3 Physical media (short but asked)

TypeMediaNote
Guided (solid raasta)Twisted pair (UTP/STP)Cat5e/Cat6 Ethernet, sasta, 100m limit, twisting se crosstalk kam
Coaxial cableCable TV/Internet, shared broadcast medium
Fiber opticLight se data, very high bandwidth, low error rate, immune to EMI, long distance — backbone ka raja
Unguided (radio)Terrestrial microwave / WiFiLAN, ~10s–100s Mbps, obstacles se affected
Cellular (4G/5G)Wide area, licensed spectrum
SatelliteGeostationary: ~270 ms propagation delay (bahut zyada!), LEO kam

1.4 Internet structure: network of networks ★★ common

Sawaal: crores ke access ISPs ko aapas mein kaise jodein? Har ISP ko har doosre se jodo to O(N²) links chahiye — impossible. Isliye hierarchy bani:

        Tier-1 ISPs (global: AT&T, Level3/Lumen, Tata Comm.)  ← ye ek doosre se
             │        peer karte hain, kisi ko paise nahi dete
        Regional ISPs (country/state level)
             │
        Access ISPs (Jio, Airtel, local broadband)  → tum yahan ho
             │
        You

  Side-by-side: IXP (Internet Exchange Point) — jahan bahut saare ISPs
  ek jagah milke traffic exchange karte hain (sasta, kam latency).
  Content Provider Networks (Google, Netflix, Akamai) — apna private
  network + CDN banate hain, aur seedha access ISPs se peer karte hain
  taaki Tier-1 ko paise na dena pade aur latency kam ho.
    
Do relationships yaad rakho

Customer–Provider: chhota ISP bade ko paise deta hai transit ke liye. Peering (settlement-free): do same-level ISPs bina paise ke traffic exchange karte hain — dono ka faayda.

1.5 Circuit switching vs Packet switching ★★★ asked a lot

Analogy

Circuit switching = train ka reserved coach. Chalne se pehle poora coach tumhare naam reserve, koi aur nahi baith sakta — chahe tum so rahe ho ya khaali seat ho. Guaranteed comfort, but waste.

Packet switching = normal bus. Jo bhi aaya, chad gaya. Kabhi khaali kabhi thusa hua. Efficient, but rush hour mein khade hoke jaana padega (queuing delay).

Circuit switchingPacket switching
Resource allocationReserved (dedicated) pehle seOn-demand, shared
Setup phaseZaroori (call setup)Nahi
PerformanceGuaranteed, constant rateBest-effort, variable
Idle time meinBandwidth wasteKoi waste nahi
CongestionNahi (par call blocked ho sakti hai)Ho sakti hai → queuing delay, packet loss
Sharing techniqueFDM / TDMStatistical multiplexing
ExampleTraditional telephone networkInternet

FDM (Frequency Division Multiplexing): har user ko alag frequency band, poore time ke liye. TDM (Time Division Multiplexing): time ko frames mein baanta, har user ko har frame mein ek fixed slot.

Packet switching kyun jeeta — ye exact answer bolna
  1. Simplicity — koi call setup nahi, network core simple rehta hai.
  2. Efficiency (statistical multiplexing) — bursty traffic ke liye perfect. Users ka data burst mein aata hai, sab ek saath nahi bolte, to same link zyada users handle kar leta hai.
  3. Trade-off: excessive congestion pe delay aur loss ho sakta hai — isliye reliable delivery ke liye upar TCP lagana padta hai.
Q1. 1 Mbps link hai. Har user active hone par 100 kbps chahiye, aur har user sirf 10% time active rehta hai. Circuit switching se kitne users? Packet switching se 35 users hone par "kitne bhi 11+ active honge" ki probability?classic

Circuit switching: har user ko 100 kbps permanently reserve karna padega → 1 Mbps / 100 kbps = 10 users. Bas. 11th user ko mana kar do.

Packet switching: 35 users allow kar do. Link tabhi overload hoga jab 11 ya zyada ek saath active hon (kyunki 10×100 kbps = 1 Mbps capacity hai).

Har user independently 0.1 probability se active hai → binomial distribution:

Formula P(n active out of N) = C(N,n) · pn · (1−p)N−n
P(>10 active) = 1 − Σn=0..10 C(35,n)(0.1)n(0.9)35−n ≈ 0.0004

Conclusion: packet switching 3.5× zyada users ko support kar raha hai, aur overload hone ka chance sirf 0.04% hai. Yehi statistical multiplexing ki taakat hai — bolna mat bhoolna.

Q2. 640,000 bits ki file bhejni hai. Circuit-switched network hai jisme har link 1.536 Mbps hai, 24 TDM slots hain, aur circuit establish hone mein 500 ms lagte hain. Total time?numerical

Step 1 — ek slot ka rate: link 24 slots mein banta hai → 1.536 Mbps / 24 = 64 kbps per circuit.

Step 2 — transmission time: 640,000 bits / 64,000 bps = 10 s.

Step 3 — setup add karo: 10 s + 0.5 s = 10.5 s.

(Propagation delay ignore kiya gaya hai question mein. Agar diya ho to wo bhi add karna.)

Interview mein kya bolna hai — Section 01
  • Internet = network of networks; edge (hosts) + access network + core (routers).
  • Protocol = format + order + actions.
  • Routing = path decide karna (global, control plane); forwarding = packet ko output port pe bhejna (local, data plane).
  • Packet switching > circuit switching kyunki bursty traffic mein statistical multiplexing zyada users support karta hai, setup nahi chahiye — trade-off congestion/queuing hai.
02 · architecture

Layering: OSI model aur TCP/IP model

Sabse zyada poochha jaane wala theory question. Yahan galti nahi honi chahiye.

08162431

2.1 Layering kyun? ★★★ asked a lot

Analogy — airline system

Ticket kharidna → baggage check-in → boarding gate → runway takeoff → airplane routing. Har step apna kaam karta hai aur destination pe ulta order mein khulta hai (landing → gate → baggage claim → ticket complain). Har layer ko sirf apne "peer layer" se matlab hai. Agar airline check-in ka process badal de, to pilot ko farq nahi padta — yehi modularity hai.

  • Modularity — har layer independently change/upgrade ho sakti hai (jaise IPv4 → IPv6 ke liye HTTP badalna nahi pada).
  • Abstraction — upar wali layer ko neeche ka implementation nahi pata, sirf service pata hai.
  • Debugging aasan — problem kis layer par hai, isolate kar sakte ho.
  • Nuksaan: thoda overhead (har layer apna header lagati hai), aur kabhi kabhi ek hi kaam do layers karti hain (error check L2 pe bhi, L4 pe bhi).

2.2 OSI 7 layers

#LayerKaam (ek line)PDUExamples
7ApplicationUser ko network services deti haiMessage/DataHTTP, DNS, SMTP, FTP
6PresentationTranslation, encryption, compression (data ka "roop")DataSSL/TLS, JPEG, ASCII
5SessionSession establish/manage/terminate, checkpointingDataNetBIOS, RPC
4TransportProcess-to-process delivery, reliability, flow & congestion controlSegment (TCP) / Datagram (UDP)TCP, UDP
3NetworkHost-to-host delivery across networks, routing, addressingPacket/DatagramIP, ICMP, OSPF, BGP
2Data LinkNode-to-node delivery on one link, framing, MAC, error detectionFrameEthernet, WiFi, ARP, PPP
1PhysicalBits ko signal (voltage/light/radio) mein badalnaBitCables, hubs, repeaters, RS-232

Mnemonic (top→bottom): All People Seem To Need Data Processing.

2.3 TCP/IP model (jo asli mein chalta hai)

  OSI (7)                       TCP/IP (5-layer, Kurose)      TCP/IP (4-layer, RFC)
  ┌─────────────┐
  │ Application │ ┐
  ├─────────────┤ │
  │Presentation │ ├──────────►  Application            Application
  ├─────────────┤ │
  │  Session    │ ┘
  ├─────────────┤
  │  Transport  │ ──────────►  Transport              Transport
  ├─────────────┤
  │  Network    │ ──────────►  Network                Internet
  ├─────────────┤
  │  Data Link  │ ──────────►  Link          ┐
  ├─────────────┤                               ├──►  Network Access
  │  Physical   │ ──────────►  Physical      ┘
  └─────────────┘
    
Common galti

OSI ek reference model hai (theory, ISO ne banaya) — Internet OSI pe nahi chalta. Internet TCP/IP model pe chalta hai, jo pehle bana aur practical hai. TCP/IP mein presentation aur session ki functionality application ke andar hi hai (jaise TLS library, HTTP cookies/sessions).

2.4 Encapsulation — packet ke upar layers ke header ★★★ asked a lot

 Sender pe (neeche jaate hue header lagta hai — "encapsulation"):

 App:    [                    Message (e.g. HTTP GET)                  ]
 Trans:  [ TCP hdr |               Message                            ]  → segment
 Net:    [ IP hdr  | TCP hdr |     Message                            ]  → datagram
 Link:   [ Eth hdr | IP hdr  | TCP hdr | Message | Eth trailer(CRC) ]  → frame
 Phy:    101101000111010101110100…                                          → bits

 Receiver pe ulta: har layer apna header hata ke upar bhejti hai — "decapsulation".
    
Yaad rakhne layak numbers

TCP header = 20 bytes minimum (max 60). IP header = 20 bytes minimum (max 60). UDP header = 8 bytes fixed. Ethernet header = 14 bytes + 4 byte CRC trailer.

Matlab HTTP data ke upar TCP/IP ka minimum overhead = 40 bytes per packet.

Q1. Router kis layer tak process karta hai? Switch? Hub?must know
DeviceLayerKis address pe kaamCollision domainBroadcast domain
Hub / RepeaterL1 PhysicalKuchh nahi — bas signal repeat1 (sab share karte hain)1
Bridge / SwitchL2 Data LinkMAC addressPer port 1 (separate)1 (VLAN se toda ja sakta hai)
RouterL3 NetworkIP addressPer port 1Per port 1 (broadcast rok deta hai)

Ek line answer: "Router L3 tak process karta hai (IP header dekh ke routing), switch L2 tak (MAC table se forwarding), hub sirf L1 (dumb signal repeater, sab ports pe bhej deta hai)."

Q2. Ek packet source se destination tak jaata hai aur beech mein 3 routers hain. Kitni baar encapsulation/decapsulation hoti hai?conceptual

Source host pe pura stack neeche jaata hai (App→Phy) = 1 full encapsulation. Har router pe packet sirf L1→L2→L3 tak upar aata hai (IP header dekhne ke liye), phir naya link-layer frame banake L3→L2→L1 neeche jaata hai. Destination pe pura stack upar (Phy→App) = 1 full decapsulation.

Key insight: Router pe L2 frame har hop pe naya banta hai (naye source/destination MAC ke saath), lekin IP header wahi rehta hai (source IP aur destination IP end-to-end same rehte hain, sirf TTL aur checksum badalta hai). Ye ARP section mein bahut kaam aayega.

Interview mein kya bolna hai — Section 02
  • 7 OSI layers naam + kaam + PDU (message/segment/packet/frame/bit) — fluently bolna aana chahiye.
  • Internet TCP/IP model use karta hai; OSI sirf reference model hai.
  • Encapsulation: har layer neeche jaate waqt header add karti hai.
  • Router = L3 (IP), Switch = L2 (MAC), Hub = L1. Router broadcast domain todta hai, switch collision domain todta hai.
03 · performance

Delay, throughput aur packet loss

Yahan se numericals aate hain — GATE, on-campus test, aur SDE interviews teeno mein.

08162431

3.1 Chaar tarah ke delay ★★★ asked a lot

        A ──────────────► [ROUTER] ──────────────► B
                          ↑  ↑  ↑  ↑
                          │  │  │  └─ 4. propagation (link pe travel)
                          │  │  └──── 3. transmission (bits ko link pe push)
                          │  └─────── 2. queuing (buffer mein wait)
                          └────────── 1. processing (header check, output link decide)
    
Yaad rakho — ye 4 formulas dtotal = dproc + dqueue + dtrans + dprop

dtrans = L / R    (L = packet length in bits, R = link bandwidth in bps)
dprop = d / s    (d = link ki physical length, s = signal speed ≈ 2×108 m/s copper/fiber mein)
dproc = typically microseconds
dqueue = variable, congestion pe depend karta hai
Transmission vs Propagation — ye sabse zyada confuse hota hai

Transmission delay = packet ke saare bits ko link par chadhaane mein laga time. Ye link ki speed (R) aur packet size (L) pe depend karta hai. Distance se koi lena-dena NAHI.

Propagation delay = ek bit ko ek chhor se doosre chhor tak pahunchne mein laga time. Ye distance aur medium pe depend karta hai. Packet size se koi lena-dena NAHI.

Caravan analogy (Kurose ki famous)

10 gaadiyon ka kaafila = ek packet ke 10 bits. Toll booth = router. Toll booth ek gaadi ko 12 sec mein process karta hai = transmission delay (poore kaafile ke liye 10×12 = 120 s). Toll booth se agle toll booth tak 100 km ka safar 100 km/h pe = 1 hour = propagation delay.

Note: agla toll booth tab tak shuru nahi karta jab tak poora kaafila (poora packet) na aa jaye — yehi store-and-forward hai.

3.2 Queuing delay aur traffic intensity

Traffic intensity Traffic intensity = L·a / R
L = packet length (bits), a = average packet arrival rate (packets/sec), R = link bandwidth (bps)
  • La/R ≈ 0 → average queuing delay bahut kam.
  • La/R → 1 → delay tezi se badhta hai (exponentially).
  • La/R > 1 → jitna aa raha hai utna nikal nahi sakta → queue infinite badhegi → packet drop. Design rule: traffic intensity ko 1 ke paas mat jaane do.
 avg queuing
   delay │           ╱
         │          ╱
         │        ╱
         │     ╱
         │ ╱
         └────────────── La/R
         0            1
    

3.3 Packet loss

Router ke buffer ki capacity finite hai. Jab queue full ho jaye aur naya packet aaye, to packet drop ho jaata hai — yehi packet loss hai. Lost packet ya to previous node se ya source se retransmit hota hai (TCP karta hai), ya kabhi retransmit hi nahi hota (UDP).

3.4 Throughput ★★ common

Definition

Throughput = rate (bits/sec) jis par bits actually receiver tak pahunch rahe hain. Instantaneous throughput = kisi ek pal ka rate; average throughput = F bits / total time.

Bottleneck rule — ye ek line poore topic ka nichod hai Throughput = min(R1, R2, …, Rn)
End-to-end throughput = raaste ki sabse dheemi link ki speed. Chain apni sabse kamzor kadi jitni hi strong hoti hai.
Analogy

Motor pipe se tank bhar rahe ho. Ek jagah pipe patli hai — chahe baaki pipe kitni bhi moti ho, paani utna hi aayega jitna patli pipe se nikal sakta hai. Bottleneck link = wahi patli pipe.

Multiple connections sharing a link: agar 10 connections ek common link R (bottleneck) share kar rahe hain, to har ek ko R/10 milta hai (fair share). Aur agar access links Rs aur Rc hain to per-connection throughput = min(Rs, Rc, R/10).

3.5 Store-and-forward: N hops ka total delay ★★★ asked a lot

Packet switch poora packet receive karne ke baad hi forward karta hai. To agar source aur destination ke beech N links hain (yaani N−1 routers), aur sab links same rate R hain, propagation ignore karke:

One packet, N links dend-to-end = N × (L/R)   [+ propagation, queuing, processing agar diye ho]
P packets, N links (pipelining ke saath) dtotal = (N + P − 1) × (L/R)

Intuition: pehla packet ko N hops paar karne mein N×(L/R) lagta hai; uske baad har agla packet ek-ek L/R ke gap pe aata rehta hai (pipeline), to (P−1) aur.

Q1. Host A ko host B ko 100 Mbit ki file bhejni hai. Do links hain: A→R (10 Mbps, 20 km) aur R→B (5 Mbps, 100 km). Packet size 1000 bits. Signal speed 2×108 m/s. (a) End-to-end throughput? (b) File bhejne mein approx kitna time?numerical

(a) Throughput = min(10 Mbps, 5 Mbps) = 5 Mbps. Bottleneck R→B link hai.

(b) Approximate time = file size / throughput = 100 × 106 / 5 × 106 = 20 seconds.

Propagation delay check karte hain — kya ye matter karta hai? dprop1 = 20,000/2×108 = 0.1 ms; dprop2 = 100,000/2×108 = 0.5 ms. Total 0.6 ms — 20 s ke saamne negligible.

Lesson

Badi file transfer mein throughput/bandwidth dominate karta hai; chhoti request-response (jaise HTTP GET, DNS query) mein propagation delay/RTT dominate karta hai. Interview mein ye nuance bolo — impress karta hai.

Q2. 1500-byte packet, 2 Mbps link, 5000 km distance, propagation speed 2.5×108 m/s. Transmission delay aur propagation delay nikalo. Kaun bada hai?numerical

dtrans = L/R = (1500 × 8 bits) / (2 × 106 bps) = 12000/2000000 = 6 ms

dprop = d/s = 5 × 106 m / 2.5 × 108 m/s = 20 ms

Propagation zyada hai. Long-distance link pe generally propagation dominate karta hai; short high-speed LAN mein transmission dominate karta hai.

Q3. 10 packets, 3 links (2 routers beech mein), har link 1 Mbps, packet size 1000 bits. Total time (propagation ignore)?numerical

L/R = 1000/106 = 1 ms. N = 3 links, P = 10 packets.

d = (N + P − 1) × L/R = (3 + 10 − 1) × 1 ms = 12 × 1 = 12 ms

Verify karke dekho: pehla packet 3 ms mein B pahunchta hai. Uske baad har 1 ms mein ek aur packet aata rehta hai → 9 aur packets ke liye 9 ms. Total 3 + 9 = 12 ms. ✓

Q4. traceroute kaise kaam karta hai? Aur ping?★★ common

traceroute: source har router tak pahunchne ke liye TTL trick use karta hai. Wo 3 packets bhejta hai TTL=1 ke saath → pehla router TTL ko 0 karke drop kar deta hai aur ICMP Time Exceeded (Type 11) message wapas bhejta hai. Us message se source ko pehle router ka IP aur RTT mil jaata hai. Phir TTL=2, TTL=3… karke har hop ka pata chal jaata hai. Jab destination pahunchta hai to wo ICMP Port Unreachable (Type 3) bhejta hai (kyunki traceroute ek weird high UDP port pe bhejta hai) — tab pata chalta hai ki manzil aa gayi.

ping: ICMP Echo Request (Type 8) bhejta hai, destination Echo Reply (Type 0) bhejta hai. Isse RTT aur packet loss % milta hai.

Windows ka tracert ICMP Echo use karta hai, Linux traceroute by default UDP. Ye detail bonus point deta hai.

Interview mein kya bolna hai — Section 03
  • 4 delays: processing, queuing, transmission (L/R), propagation (d/s). Transmission ≠ propagation — ye distinction saaf bolna.
  • Throughput = bottleneck link ka min.
  • Store-and-forward N links: N·L/R; P packets: (N+P−1)·L/R.
  • Traffic intensity La/R → 1 hone pe queuing delay blow up ho jaata hai, >1 pe loss.
04 · application layer

Application layer aur HTTP

Jahan tumhari app rehti hai. HTTP interview ka sabse favourite protocol hai.

08162431

4.1 Application architectures

ArchitectureKaise kaam karta haiPros / ConsExample
Client–ServerAlways-on server, fixed IP; clients server se baat karte hain, aapas mein nahi. Scale ke liye data center.+ Simple, manage karna aasan
− Server bottleneck, scaling mehnga
Web, email, banking
Pure P2PKoi always-on server nahi; peers direct baat karte hain, intermittently connected, IP badalte rehte hain.+ Self-scalable (naya peer capacity bhi laata hai)
− Manage/secure karna mushkil
BitTorrent
HybridServer sirf lookup/index/login ke liye, data transfer P2P.Dono ke faaydeSkype (purana), Napster

4.2 Process communication: socket aur addressing

Socket

Socket = application process aur transport layer ke beech ka door / interface (API). App socket se message bahar dhakelti hai; uske baad transport layer sambhal leti hai. Process socket ke bahar kuch control nahi kar sakti (sirf transport protocol choose kar sakti hai aur kuch parameters set kar sakti hai).

Process ko identify kaise karein?

Sirf IP address kaafi nahi — ek host pe bahut saare processes chal rahe hain. Isliye chahiye: IP address + Port number. Isi jodi ko socket address kehte hain.

Well-known ports: HTTP 80, HTTPS 443, SSH 22, Telnet 23, SMTP 25, DNS 53, DHCP 67/68, TFTP 69, POP3 110, IMAP 143, SNMP 161, FTP 20 (data) / 21 (control), MySQL 3306, RDP 3389.

App ko transport se kya chahiye?

RequirementMatlabLoss-tolerant appLoss-sensitive app
Data integrity100% reliable delivery chahiye ya nahiAudio/video streamingFile transfer, web, email
Timing / LatencyLow delay chahiyeGames, VoIP: haan (<100 ms). Email: nahi.
ThroughputMinimum bandwidth guaranteeVideo: "elastic nahi", minimum chahiye. Email/web: elastic, jitna mile chalega.
SecurityEncryption, integrityTLS se milta hai (transport ke upar)

Internet ka TCP ye deta hai: reliable, in-order, flow control, congestion control — par timing ya minimum bandwidth guarantee nahi deta. Ye line interview mein bolna.

4.3 HTTP basics ★★★ asked a lot

  • HyperText Transfer Protocol — web ka application layer protocol, client-server model.
  • TCP use karta hai, port 80 (HTTPS: 443). Pehle TCP connection banega, phir HTTP messages.
  • Stateless — server client ke pichle requests ke baare mein kuch yaad nahi rakhta. (Isliye cookies ki zaroorat padi.)
  • Web page = ek base HTML file + N referenced objects (images, CSS, JS). Har object ka apna URL.
"HTTP stateless hai" ka asli matlab

Stateless matlab protocol khud state nahi rakhta — har request independent hai. Iska matlab ye NAHI ki websites tumhe pehchaan nahi sakti. Wo state application level pe rakhi jaati hai — cookies, sessions, tokens (JWT), URL rewriting. Interview mein pucha jaye "HTTP stateless hai to login kaise yaad rehta hai?" → answer: cookies/session ID.

4.4 Non-persistent vs Persistent HTTP ★★★ asked a lot

Non-persistent (HTTP/1.0)Persistent (HTTP/1.1 default)
TCP connectionHar object ke liye nayi connection, phir bandEk hi connection pe saare objects
Objects per connection1Multiple
OS overheadZyada (har connection ke liye buffers/variables)Kam
Slow start penaltyHar baar TCP slow start se shuruEk baar window bada ho gaya to fayda
Time for N objects2·RTT per object1·RTT per object (pipelining ke saath ~1 RTT total)
Header—Connection: keep-alive (1.1 mein default)
RTT formulas — ratt lo Non-persistent, no parallel: Total = 2·RTT + (N × 2·RTT) + transmit times
  → 1 RTT TCP handshake + 1 RTT request/response, base file ke liye; phir har object ke liye phir se 2 RTT

Persistent without pipelining: Total = 2·RTT + N × RTT
Persistent with pipelining: Total = 2·RTT + 1·RTT (sab requests ek saath)
Non-persistent with X parallel connections: 2·RTT + ⌈N/X⌉ × 2·RTT
Q1. Ek web page mein 1 base HTML + 5 chhoti images hain. RTT = 100 ms, transmission time ignore. Time nikalo: (a) non-persistent serial, (b) non-persistent with 5 parallel connections, (c) persistent with pipelining.super classic

(a) Non-persistent, serial: base file ke liye 2 RTT (1 handshake + 1 request/response) = 200 ms. Phir har image ke liye 2 RTT × 5 = 1000 ms. Total = 2 RTT + 10 RTT = 12 RTT = 1200 ms.

(b) Non-persistent, 5 parallel: base file 2 RTT. Phir 5 images ek saath 5 parallel connections pe = sirf 2 RTT. Total = 4 RTT = 400 ms.

(c) Persistent with pipelining: 1 RTT handshake + 1 RTT base HTML + 1 RTT saari 5 images ek saath. Total = 3 RTT = 300 ms.

Persistent+pipelining sabse fast, aur ek hi TCP connection use karta hai — server pe load bhi kam. Isliye HTTP/1.1 ne isko default banaya.

4.5 HTTP message format

REQUEST
GET /somedir/page.html HTTP/1.1        ← request line: METHOD  URL  VERSION
Host: www.someschool.edu              ← header lines
Connection: close
User-Agent: Mozilla/5.0
Accept-language: en
(blank line = CR LF)
(entity body — POST/PUT mein data yahan)

RESPONSE
HTTP/1.1 200 OK                       ← status line
Date: Tue, 09 Aug 2026 15:44:04 GMT
Server: Apache/2.4.41
Last-Modified: Tue, 09 Aug 2026 15:11:03 GMT
Content-Length: 6821
Content-Type: text/html
(blank line)
<html> … data … </html>              ← entity body
    

HTTP methods

MethodKaamSafe?Idempotent?
GETResource fetch karo; parameters URL meinHaanHaan
POSTData server ko bhejo (form submit); data body meinNahiNahi
PUTResource ko poora replace/upload karoNahiHaan
PATCHResource ko partially update karoNahiNahi
DELETEResource delete karoNahiHaan
HEADGET jaisa par sirf headers, body nahi (debug/cache check)HaanHaan
OPTIONSServer kya-kya support karta hai (CORS preflight)HaanHaan
Idempotent ka matlab (interview mein poochha jaata hai)

Ek hi request 1 baar bhejo ya 100 baar — server ka final state same rahega. DELETE idempotent hai (pehli baar delete hua, baaki baar "already gone"). POST idempotent nahi (5 baar order place karoge to 5 order ban jayenge).

Safe = server ka state bilkul badalta hi nahi (read-only).

GET vs POST ★★★ asked a lot

GETPOST
Data kahanURL query string mein (?a=1&b=2)Request body mein
Length limitURL length limit (~2000 chars practical)Practically unlimited
Cache/bookmark/historyHo sakta haiNahi
SecurityURL logs/history mein dikh jaata hai — sensitive data ke liye galatBetter (par bina HTTPS ke dono plaintext hi hain!)
IdempotentHaanNahi

Status codes — ye poochhe jaate hain

ClassCodeMatlab
1xx Info100 ContinueAage bhejo
2xx Success200 OKSab theek, object attached
201 Created / 204 No ContentBana diya / kuch return nahi
3xx Redirect301 Moved PermanentlyNaya URL, hamesha ke liye
302 / 307 Found / Temporary RedirectAbhi ke liye kahin aur
304 Not ModifiedCache valid hai, apni copy use karo (conditional GET ka reply)
4xx Client error400 Bad RequestRequest samajh nahi aayi
401 Unauthorized / 403 ForbiddenLogin chahiye / access mana hai
404 Not FoundDocument nahi mila
429 Too Many RequestsRate limit
5xx Server error500 Internal Server ErrorServer crash/bug
502 Bad Gateway / 503 Service UnavailableUpstream kharab / server down-overloaded
504 Gateway TimeoutUpstream ne time pe jawab nahi diya

4.6 Cookies — stateless protocol mein state ★★ common

  1. Pehli baar tum site pe jaate ho. Server ek unique ID generate karta hai aur backend database mein entry banata hai.
  2. Response mein header aata hai: Set-Cookie: 1678
  3. Browser use apni cookie file mein save kar leta hai (domain ke against).
  4. Aage har request mein browser bhejta hai: Cookie: 1678
  5. Server us ID se tumhe pehchaan leta hai → shopping cart, login session, recommendations.

Cookies ke 4 kaam: authorization, shopping carts, recommendations, user session state.

Third-party cookies aur tracking

Agar page pe koi ad-network ka image/script hai (jaise adx.com), to browser us domain ko bhi request bhejta hai aur uski cookie set ho jaati hai. Ab tum jis bhi site pe jaoge jahan adx.com ka ad hai, wo same cookie dekh kar tumhari browsing history joint kar lega. Yehi third-party cookie tracking hai — isi wajah se browsers ise band kar rahe hain.

Cookie vs Session vs Token

Cookie = client-side storage mechanism. Session = server-side state, jiska ID cookie mein jaata hai. JWT token = self-contained signed token, server ko state store karne ki zaroorat nahi (stateless auth).

4.7 Web caching (proxy server) ★★ common

Cache = client ke paas wala server jo popular objects ki copy rakhta hai. Browser saari requests cache ko bhejta hai. Agar object cache mein hai → turant de deta hai. Nahi hai → cache origin server se laata hai, apne paas rakhta hai, aur client ko deta hai.

  • Faayde: response time kam, institutional access link ka traffic kam (paisa bachta hai), origin server pe load kam.
  • Cache client bhi hai aur server bhi — origin ke liye client, browser ke liye server.
  • CDN (Akamai, Cloudflare) yehi cache ko global scale pe karte hain.

Conditional GET — cache stale na ho jaye

 Cache → Server:   GET /fruit/kiwi.gif HTTP/1.1
                   If-Modified-Since: Wed, 7 Sep 2026 09:23:24

 Agar object badla nahi:        Agar object badal gaya:
 HTTP/1.1 304 Not Modified       HTTP/1.1 200 OK
 (body khaali — bandwidth bacha)   (naya object body mein)
    

Modern version: ETag + If-None-Match (hash-based, timestamp se better). Cache-Control: max-age=3600 se to network trip hi nahi hoti.

Q2. Institution ka LAN 100 Mbps hai, access link to Internet 15 Mbps, Internet delay 2 sec. Average object size 1 Mbit (1,000,000 bits), request rate 15 requests/sec. (a) Access link utilization? (b) Total response time? (c) Cache lagane se (hit rate 40%) kya hoga?classic numerical

(a) Utilization:

  • LAN utilization = (15 req/s × 1 Mbit) / 100 Mbps = 15/100 = 0.15 → thik hai.
  • Access link utilization = 15 Mbps / 15 Mbps = 0.99+ (~1.0) → ye problem hai! Utilization 1 ke paas → queuing delay minutes mein chala jaata hai.

(b) Total response time = LAN delay + access link delay + Internet delay = milliseconds + minutes + 2 sec = minutes. Bekaar experience.

(c) Cache with 40% hit rate:

  • 40% requests cache se satisfied → delay ~ LAN delay only ≈ 0.01 sec.
  • 60% requests origin se → access link pe traffic = 0.6 × 15 Mbps = 9 Mbps → utilization = 9/15 = 0.6 → queuing delay ab manageable (~0.01 s).
  • Average = 0.4 × (0.01) + 0.6 × (2.01) ≈ 1.2 sec

Conclusion: Cache lagana access link ko 15→100 Mbps upgrade karne se sasta bhi hai aur similar effect deta hai. Interview mein yahi trade-off bolna.

4.8 HTTP versions: 1.1 → 2 → 3 ★★ common

Head-of-Line (HOL) blocking — do jagah hoti hai, confuse mat karna

HTTP/1.1 mein (application-level HOL): ek TCP connection pe requests FCFS order mein serve hoti hain. Agar pehla object bada video hai, to peeche ke 3 chhote objects wait karte rahenge — bhale wo ready hon.

HTTP/2 mein (transport-level HOL): HTTP/2 ne application-level HOL solve kar diya (frames interleave karke), lekin TCP still in-order delivery deta hai — agar ek TCP segment kho gaya, to uske baad ke saare streams ka data OS buffer mein ruka rehta hai jab tak retransmission na aa jaye. Ye TCP-level HOL blocking hai, jise sirf QUIC (HTTP/3) solve karta hai.

HTTP/1.1HTTP/2HTTP/3
TransportTCPTCPQUIC over UDP
FormatTextBinary framingBinary
MultiplexingNahi (pipelining buggy thi)Haan — ek connection pe multiple streams, frames interleavedHaan, independent streams
App-level HOLHaanSolvedSolved
Transport-level HOLHaanHaan (TCP ki wajah se)Solved (per-stream loss recovery)
Header compressionNahiHPACKQPACK
Server push / priorityNahiHaanHaan
Handshake RTTs1 (TCP) + 2 (TLS)Same1 RTT, ya 0-RTT resume (TCP+TLS merged)
Connection migration (WiFi→4G)Connection toot jaata haiToot jaata haiConnection ID se survive karta hai

HTTP/2 vocabulary: Stream = ek bidirectional flow of bytes ek connection ke andar (har request-response ka apna stream ID). Frame = sabse chhoti unit (HEADERS, DATA, SETTINGS…). Objects ko frames mein toda jaata hai aur frames interleave karke bheje jaate hain — isliye chhota object bade object ke peeche atakta nahi.

4.9 HTTPS aur TLS (bonus but poochha jaata hai) ★★★ asked a lot

HTTPS = HTTP + TLS (Transport Layer Security, purana naam SSL). Port 443. TLS TCP ke upar aur HTTP ke neeche baithta hai.

TLS kya deta hai: (1) Confidentiality — encryption, (2) Integrity — MAC se tampering pakadna, (3) Authentication — certificate se server ki pehchaan.

  1. ClientHello — client supported cipher suites aur random number bhejta hai.
  2. ServerHello + Certificate — server cipher choose karta hai, apna X.509 certificate (public key + CA ka signature) bhejta hai.
  3. Client CA chain verify karta hai (browser mein pre-installed root CAs se).
  4. Key exchange — client pre-master secret banata hai (RSA se encrypt karke bhejta hai, ya modern mein ECDHE se dono milke derive karte hain — forward secrecy ke liye).
  5. Dono taraf symmetric session key derive hoti hai. Actual data symmetric encryption (AES) se hota hai kyunki wo fast hai.
  6. Finished messages — handshake verify, phir encrypted application data start.
Ek line answer

"TLS asymmetric crypto ka use sirf handshake mein karta hai — authentication aur ek shared symmetric key establish karne ke liye. Uske baad saara data symmetric key (AES) se encrypt hota hai kyunki asymmetric bahut slow hai."

Q3. HTTP stateless hai to phir login session kaise maintain hota hai? Aur cookie chura li jaye to?★★★ asked a lot

Login ke baad server ek session ID (ya JWT) banata hai aur Set-Cookie se client ko bhej deta hai. Har agli request mein browser wo cookie automatically bhejta hai, server usse user pehchaanta hai. Protocol tab bhi stateless hai — state application layer pe rakhi hai.

Cookie chori (session hijacking) se bachne ke tareeke:

  • Secure flag — cookie sirf HTTPS pe jayegi.
  • HttpOnly flag — JavaScript cookie ko padh nahi sakti (XSS se bachav).
  • SameSite=Strict/Lax — cross-site request pe cookie nahi jayegi (CSRF se bachav).
  • Short expiry + rotation, aur server-side session invalidation.
Q4. Ek hi TCP connection pe HTTP/1.1 se 4 objects mangwaye — 1 bada (video) aur 3 chhote. Kya hoga? HTTP/2 kaise better karta hai?conceptual

HTTP/1.1: requests FCFS. Bada video pehle aaya to 3 chhote objects uske poora transfer hone tak wait karenge — HOL blocking. Isliye browsers 6 parallel TCP connections kholte the (hack).

HTTP/2: har object ka apna stream hai; server har object ko chhote frames mein todta hai aur frames ko interleave karke bhejta hai. Chhote objects jaldi complete ho jaate hain. Upar se priority set kar sakte ho (CSS/JS pehle, image baad mein) aur headers HPACK se compress hote hain.

Baaki bacha problem: agar TCP segment loss ho gaya to poori connection ruk jaati hai (TCP HOL) — wo HTTP/3/QUIC solve karta hai.

Interview mein kya bolna hai — Section 04
  • HTTP = stateless, TCP port 80/443, request/response model. State cookies se aati hai.
  • Persistent connection HTTP/1.1 ka default; non-persistent har object pe 2 RTT lagata hai.
  • GET vs POST, idempotency, status code classes (2xx/3xx/4xx/5xx) — 304 aur 301 ka role.
  • Cache + conditional GET (If-Modified-Since / ETag) se bandwidth aur latency dono bachte hain.
  • HTTP/2 = binary + multiplexed streams (app HOL fix); HTTP/3 = QUIC over UDP (transport HOL fix + 0-RTT + connection migration).
  • HTTPS = TLS: asymmetric se handshake/auth, symmetric se data.
05 · application layer

DNS — Internet ki phone book

Har interview mein aata hai, aur "google.com type karne pe kya hota hai" ka pehla step yahi hai.

08162431

5.1 DNS kya karta hai

Definition

Domain Name System = ek distributed, hierarchical database + ek application-layer protocol, jo hostname (www.google.com) ko IP address (142.250.x.x) mein translate karta hai. UDP port 53 pe chalta hai.

DNS ki services:

  • Hostname → IP address translation (main kaam)
  • Host aliasing — canonical name vs alias (relay1.west.enterprise.com ↔ www.enterprise.com)
  • Mail server aliasing — MX records
  • Load distribution — ek hostname ke liye multiple IPs, rotate karke return karta hai (poor man's load balancer)
DNS centralized kyun nahi? (favourite question)
  1. Single point of failure — wo server gira to pura Internet gira.
  2. Traffic volume — duniya ki saari DNS queries ek server handle nahi kar sakta.
  3. Distance — India ka user agar US ke server ko query kare to latency bahut zyada.
  4. Maintenance — ek hi database mein crores entries update karna impossible.

5.2 DNS hierarchy ★★★ asked a lot

                        Root DNS servers  (13 logical: a.root-servers.net … m,
                             │           actually 1000+ physical via anycast)
        ┌────────────────────┼────────────────────┐
     .com TLD            .org TLD            .in TLD       ← Top Level Domain servers
        │                    │                    │
   google.com          wikipedia.org      bits-pilani.ac.in  ← Authoritative servers
   authoritative                                              (organization ke apne records)

  + Local DNS server / Resolver (ISP ya 8.8.8.8) — hierarchy ka hissa nahi,
    par har query pehle yahin jaati hai; ye cache rakhta hai aur pura kaam karwata hai.
    
  • Root server — TLD server ka pata deta hai. (ICANN manage karta hai Verisign ke saath.)
  • TLD server — .com, .org, .edu, country domains (.in, .uk). Authoritative server ka pata deta hai.
  • Authoritative server — organization ka apna DNS server, jisme uske hosts ke actual records hain. Final answer yahin se aata hai.
  • Local DNS server (resolver) — ISP ka server (ya Google 8.8.8.8, Cloudflare 1.1.1.1). Cache aur proxy dono ka kaam karta hai.

5.3 Iterative vs Recursive query ★★★ asked a lot

Recursive
Host → Local DNS: "IP bata do"
Local → Root:    "IP bata do"
Root  → TLD:     "IP bata do"
TLD   → Auth:    "IP bata do"
       ← ← ← ← answer wapas chain se

Har server khud aage poochhta hai aur poora answer laata hai. Load upper-level servers pe zyada padta hai.

Iterative (real world mein yehi hota hai)
Host  → Local DNS: "IP bata do" (recursive)
Local → Root: → "mujhe nahi pata,
                 TLD se poochho"
Local → TLD:  → "auth server se poochho"
Local → Auth: → "ye rahi IP"
Local → Host: "ye rahi IP"

Server bolta hai "mujhe nahi pata, ussey poochho". Local DNS server hi mehnat karta hai.

Practice mein kya hota hai

Client → local DNS server tak query recursive hoti hai. Local DNS server → root/TLD/authoritative tak queries iterative hoti hain. Ye exact line bolna interview mein.

5.4 DNS caching

  • Koi bhi DNS server jo mapping seekhta hai, use cache kar leta hai.
  • Har record ke saath TTL (Time To Live) hoti hai — utni der baad entry delete ho jaati hai.
  • Isi wajah se root servers pe traffic bahut kam hai — TLD mappings local servers mein cached rehti hain.
  • Downside: agar koi host apni IP badal le, to purani cached entry TTL expire hone tak galat rahegi (isliye migration se pehle TTL kam kar dete hain).
  • Caching layers: browser cache → OS cache → local resolver cache.

5.5 DNS records (RR = Resource Record)

Format: (Name, Value, Type, TTL)

TypeNameValueKaam
AhostnameIPv4 addressSabse basic mapping
AAAAhostnameIPv6 addressIPv6 ke liye
NSdomainauthoritative server ka hostnameQuery ko aage bhejne ke liye
CNAMEalias hostnamecanonical hostnameAlias → asli naam
MXdomainmail server ka nameEmail routing
PTRIP addresshostnameReverse DNS lookup
TXTdomainarbitrary textSPF/DKIM (email spam), domain verification
SOAzonezone infoZone ka master record

5.6 DNS message + transport

  • Query aur reply ka same format hota hai: Header (identification, flags) + Question + Answer + Authority + Additional sections.
  • UDP port 53 — kyun UDP? Kam overhead, no handshake (fast), query chhoti hoti hai, aur retry app khud kar leti hai. Speed > reliability yahan.
  • TCP kab? Jab response 512 bytes se bada ho (ab EDNS0 se 4096 tak UDP chal jaata hai), aur zone transfers ke liye (secondary server master se pura zone copy karta hai).

5.7 Domain register karna

Registrar (GoDaddy, Namecheap) ke through domain lo → usko apne authoritative server ke NS records aur unke A records (glue records) dene padte hain → registrar unhe .com TLD server mein daal deta hai. Ab duniya tumhare server tak pahunch sakti hai.

5.8 DNS attacks (bonus, security round mein)

  • DNS spoofing / cache poisoning — attacker fake response bhej deta hai jo resolver cache kar leta hai, phir users galat IP pe redirect ho jaate hain. Fix: DNSSEC (records ko digitally sign karna).
  • DDoS on root/TLD — hua hai, par caching aur anycast ki wajah se zyada asar nahi hua.
  • DNS amplification — chhoti spoofed query se badi response victim pe bhejwana.
  • DoH / DoT — DNS over HTTPS/TLS, privacy ke liye query ko encrypt karna.
Q1. www.cse.bits.ac.in ki lookup mein pehli baar kitne DNS messages exchange hote hain (sab iterative, kuch cached nahi)? Aur agla user same domain query kare to?numerical

Pehli baar (cold cache):

  1. Host → Local DNS (query)  → 1
  2. Local → Root, Root → Local (referral to .in TLD)  → 2
  3. Local → TLD(.in), TLD → Local (referral to ac.in / bits.ac.in auth)  → 2
  4. Local → Authoritative, Auth → Local (final A record)  → 2
  5. Local → Host (answer)  → 1

Total ≈ 8 messages (4 queries + 4 responses), yaani ~4 RTTs. Agar sub-domain hierarchy aur deep ho to aur zyada.

Dusri baar: local DNS ke cache mein answer hai → sirf 2 messages (host↔local), latency almost zero. Isliye DNS caching itni important hai.

Q2. DNS UDP kyun use karta hai, TCP kyun nahi? ★★★ asked a lot
  • Speed: TCP ko 3-way handshake chahiye = 1 extra RTT + connection teardown. DNS query chhoti hoti hai, ek round-trip mein kaam ho jaana chahiye.
  • Overhead: UDP header 8 bytes vs TCP 20+ bytes; server pe connection state bhi nahi rakhni padti → ek DNS server lakhon queries handle kar leta hai.
  • Reliability ka nuksan nahi: agar response na aaye, resolver simply retry kar leta hai ya doosre server se poochh leta hai — application-level retry.
  • TCP fallback: bade responses (>512 B, ya EDNS0 limit se bada) aur zone transfer (AXFR) ke liye TCP use hota hai.
Interview mein kya bolna hai — Section 05
  • DNS = distributed hierarchical DB: root → TLD → authoritative; + local resolver jo cache karta hai.
  • Client→resolver recursive, resolver→hierarchy iterative.
  • UDP 53, TCP for large responses & zone transfer.
  • Records: A, AAAA, NS, CNAME, MX. TTL se caching control hoti hai.
  • Centralized nahi ho sakta: SPOF, traffic, distance, maintenance.
06 · application layer

Email, FTP aur P2P

SMTP/POP3/IMAP ka difference aur P2P ke distribution-time formulas.

08162431

6.1 Email ke 3 components

User agents (Outlook, Gmail UI) + Mail servers (mailbox + outgoing message queue) + SMTP (servers ke beech ka protocol).

 Alice ────SMTP───► Alice ka mail ────SMTP───► Bob ka mail ───POP3/IMAP──► Bob
 (user agent)        server                     server                    (user agent)
                  PUSH protocol                              PULL protocol
    

SMTP (Simple Mail Transfer Protocol) ★★ common

  • TCP port 25 (submission ke liye 587, SMTPS 465), reliable transfer.
  • Push protocol — sender apna message dhakelta hai (HTTP pull hai — client maangta hai).
  • 3 phases: handshaking → transfer of messages → closure.
  • Commands: HELO/EHLO, MAIL FROM, RCPT TO, DATA, QUIT. Response codes numeric (250 OK, 354 start mail input, 221 bye).
  • Historically 7-bit ASCII body; binary attachments ke liye MIME encoding (base64) chahiye.
  • Message ka end: single line with just .
  • Ek hi TCP connection pe multiple messages bhej sakta hai (persistent).
SMTP vs HTTP — classic comparison
SMTPHTTP
DirectionPushPull
Encoding7-bit ASCII (MIME se binary)Binary allowed
Multiple objectsSab ek hi multipart message meinHar object ka apna response
Port2580
CommonDono TCP use karte hain, dono persistent connections use karte hain, dono ASCII command/response format use karte hain

Mail access protocols: POP3 vs IMAP ★★ common

POP3 (port 110)IMAP (port 143)Webmail
Mail rehti kahanDownload karke local, server se delete (default)Server pe hi rehti haiServer pe
Multiple devicesProblem — ek device pe download hui to doosre pe nahi milegiPerfect — sab devices syncPerfect
FoldersNahi (stateless across sessions)Haan, server pe folders/flags (stateful)Haan
Bandwidth/storageKam server storageZyada server storageZyada
Partial fetchNahiHaan (sirf header ya ek MIME part)Haan
ProtocolPOP3IMAPHTTP/HTTPS

Note: Sending hamesha SMTP se hi hota hai, chahe tum Gmail web UI use karo (browser→Gmail server HTTP, Gmail server→receiver SMTP).

6.2 FTP — File Transfer Protocol

  • TCP, do connections: control connection port 21 (commands, "out-of-band") aur data connection port 20 (actual file).
  • Stateful — server current directory aur authentication state yaad rakhta hai (HTTP stateless hai — ye difference poochha jaata hai).
  • Control connection puri session tak khuli rehti hai; har file transfer ke liye nayi data connection banti hai.
  • Active mode: server client se data connection banata hai (client ke firewall/NAT ke liye problem). Passive mode: client hi data connection banata hai — isliye aaj passive default hai.
  • Commands: USER, PASS, LIST, RETR, STOR. Replies: 331 username OK, 425 can't open data connection, 452 error writing file.
  • Plaintext hai → aaj SFTP (SSH-based, port 22) ya FTPS use karna chahiye.

6.3 P2P file distribution ★★ common

Sawaal: ek file (size F) ko 1 server se N peers tak pahunchane mein kitna time?

Client–Server Dcs ≥ max{ N·F / us , F / dmin }
us = server upload rate, dmin = sabse dheeme client ka download rate
Server ko har peer ko alag copy bhejni padti hai → N·F upload karna hai → N ke saath linearly badhta hai.
Peer-to-Peer DP2P ≥ max{ F / us , F / dmin , N·F / (us + Σui) }
Server ko sirf ek copy upload karni hai. Total upload capacity mein har naye peer ka apna upload bhi jud jaata hai → self-scaling.
Yaad rakhne wali insight

Client-server ka time N ke saath linear badhta hai; P2P ka time N badhne pe bhi almost flat rehta hai, kyunki har naya peer demand ke saath capacity bhi laata hai. Yehi P2P ki "self-scalability" hai.

BitTorrent

  • File chunks (256 KB typical) mein toot jaati hai. Peers ka group = torrent; tracker peers ka register rakhta hai.
  • Naya peer tracker se peer list leta hai, kuch se TCP connection banata hai (neighbours).
  • Rarest first — jo chunk swarm mein sabse kam hai, wo pehle maango (taaki file swarm mein zinda rahe aur distribution balanced ho).
  • Tit-for-tat (choking): jo top-4 peers tumhe sabse tez de rahe hain, unhi ko tum bhejo ("unchoked"). Har 10 sec re-evaluate.
  • Optimistic unchoking: har 30 sec ek random naye peer ko bhi mauka do — isse naye peers shuru kar paate hain aur better partners mil sakte hain.
  • Free-riding (sirf download karna) is tarah discourage hota hai.
  • Seeder = poori file rakhne wala, Leecher = abhi download kar raha.

DHT aur Chord (short)

Problem: kis peer ke paas kaunsi file hai, ye kaise dhoondein bina central server ke? Solution: Distributed Hash Table — (key, value) pairs peers ke beech baant do. Har peer aur har key ko hash karke ek m-bit ID do; key ko us peer pe rakho jiska ID key ke successor (closest ID ≥ key) hai.

  • Circular DHT: har peer sirf successor jaanta hai → lookup O(N) messages. Simple par slow.
  • Chord with finger table: har node m entries rakhta hai (20, 21, … 2m−1 aage wale successors) → lookup O(log N).
  • Peer churn handle karne ke liye har peer apne successor ke saath-saath doosre successor ko bhi track karta hai.
Q1. F = 15 Gbits, 100 peers, us = 30 Mbps, har peer ui = 2 Mbps aur di = 10 Mbps. Client-server aur P2P distribution time nikalo.numerical

Client–Server:

  • N·F/us = (100 × 15,000 Mbit) / 30 Mbps = 1,500,000/30 = 50,000 s
  • F/dmin = 15,000/10 = 1,500 s
  • Dcs = max(50,000, 1,500) = 50,000 s ≈ 13.9 hours (server upload bottleneck)

P2P:

  • F/us = 15,000/30 = 500 s
  • F/dmin = 1,500 s
  • N·F/(us + Σui) = 1,500,000 / (30 + 100×2) = 1,500,000/230 = 6,522 s
  • DP2P = max(500, 1500, 6522) = 6,522 s ≈ 1.8 hours

P2P ~7.7× faster — aur N badhaoge to gap aur badhega.

Interview mein kya bolna hai — Section 06
  • SMTP push (25), POP3/IMAP pull (110/143). IMAP server pe rakhta hai + sync karta hai, POP3 download karke delete.
  • FTP: separate control (21) aur data (20) connections = "out-of-band control", aur stateful hai.
  • P2P self-scaling hai: Dcs N ke saath linear, DP2P saturate ho jaata hai.
  • BitTorrent: rarest-first + tit-for-tat + optimistic unchoke.
07 · transport layer

Transport layer basics, multiplexing aur UDP

Process-to-process delivery. Yahin se TCP/UDP ka khel shuru hota hai.

08162431

7.1 Transport layer ka kaam

Definition

Transport layer alag-alag hosts pe chal rahe application processes ke beech logical communication provide karta hai. "Logical" matlab app ko lagta hai jaise dono directly jude hon, chahe beech mein 20 router hon.

Transport vs Network layer — ye exact difference bolna

Network layer: host-to-host logical communication (ghar se ghar tak chitthi).

Transport layer: process-to-process logical communication (ghar ke andar sahi bande tak chitthi).

Analogy: Do gharon ke 12-12 bachche chitthi likhte hain. Postal service = network layer (ghar tak pahunchati hai). Ghar ka bada bhai jo chitthiyan collect karke lifafe mein daalta hai aur aayi hui chitthi sahi bhai ko deta hai = transport layer.

7.2 Multiplexing aur Demultiplexing ★★★ asked a lot

Multiplexing (sender pe): alag-alag sockets se data lo, har ek pe header (port numbers) lagao, aur network layer ko pass karo.
Demultiplexing (receiver pe): aaye hue segment ko dekh ke sahi socket tak pahunchao.

UDP demux — 2-tuple

UDP socket identify hota hai: (dest IP, dest port)

Agar do alag hosts se aaye segments ka dest port same hai, to dono ek hi socket pe jayenge. Source IP/port sirf reply bhejne ke liye use hote hain.

TCP demux — 4-tuple

TCP socket identify hota hai: (src IP, src port, dest IP, dest port)

Har connection ka apna alag socket. Ek server 80 port pe hazaron connections rakh sakta hai — kyunki har ek ka 4-tuple alag hai.

Q1. Ek web server port 80 pe hai. Do alag clients se 2-2 connections aati hain. Server pe kitne sockets? Kaise distinguish hote hain?must know

4 connection sockets + 1 listening socket = 5 sockets. Har connection socket ka 4-tuple alag hai:

(A:26145, S:80)   ← client A, connection 1
(A:7532,  S:80)   ← client A, connection 2   (source port alag)
(B:26145, S:80)   ← client B, connection 1   (source IP alag — port same ho to bhi chalega)
(B:9157,  S:80)   ← client B, connection 2

Isliye TCP mein 4-tuple zaroori hai — sirf dest port se demux karte to server saare clients ko ek hi socket pe daal deta.

7.3 UDP — User Datagram Protocol ★★★ asked a lot

"No frills, bare bones" transport. Best-effort service — segment lost ho sakta hai, out-of-order aa sakta hai.

 UDP header — sirf 8 bytes:
 ┌───────────────────────┬───────────────────────┐
 │  Source Port (16)     │  Dest Port (16)       │
 ├───────────────────────┼───────────────────────┤
 │  Length (16)          │  Checksum (16)        │   Length = header + data, bytes mein
 ├───────────────────────┴───────────────────────┤
 │                Application data                │
 └───────────────────────────────────────────────┘
    
UDP kyun exist karta hai? (ye 5 points bolna)
  1. No connection establishment — koi handshake nahi, koi extra RTT nahi (DNS ke liye perfect).
  2. No connection state — server pe buffers/variables nahi rakhne padte → zyada clients handle kar sakta hai.
  3. Small header — 8 bytes vs TCP ke 20.
  4. No congestion control — app jitni tezi se chahe bhej sakti hai (real-time video ke liye achha, network ke liye kabhi kabhi bura).
  5. Finer application-level control — app khud decide karti hai kya retransmit karna hai (jaise QUIC karta hai).

UDP kahan use hota hai: DNS, DHCP, SNMP, RIP, TFTP, VoIP/video streaming, online gaming, aur QUIC (HTTP/3).

UDP checksum ★★ common

  1. Segment ke contents ko 16-bit integers ki sequence maano.
  2. Sab ko jodo — 1's complement addition (carry ko wapas LSB pe add karo, "wrap around").
  3. Result ka 1's complement (sab bits invert) le lo — wahi checksum hai.
  4. Receiver saare 16-bit words + checksum ko jodta hai. Agar answer 1111111111111111 aaye → no error detected. Warna error.
Q2. Do 16-bit words hain: 1110011001100110 aur 1101010101010101. Checksum nikalo.numerical
  1110011001100110
+ 1101010101010101
──────────────────
 11011101110111011      ← 17 bits, carry nikal gaya

 wraparound: 1011101110111011 + 1 = 1011101110111100   ← sum

 checksum = 1's complement of sum = 0100010001000011

Receiver ka check: 1011101110111100 + 0100010001000011 = 1111111111111111 → sab 1s → error nahi mila. ✓

Note: checksum error detection deta hai, correction nahi. Aur ye weak hai — kuch multi-bit errors chhoot sakte hain (jaise do bits ka same position pe flip). Isliye link layer pe CRC bhi hota hai.

UDP "unreliable" hai to checksum kyun?

End-to-end principle: link layer pe error detection hoti hai, par har link pe hona guaranteed nahi (aur router ki memory mein bhi bit flip ho sakta hai). Isliye transport pe ek end-to-end check rakha gaya. UDP error detect karta hai to segment drop kar deta hai (ya warning ke saath app ko de deta hai) — recover nahi karta.

7.4 TCP vs UDP — table ratt lo ★★★ asked a lot

TCPUDP
ConnectionConnection-oriented (3-way handshake)Connectionless
ReliabilityReliable — ACK + retransmissionUnreliable, best effort
OrderingIn-order delivery guaranteedNo ordering
Header size20–60 bytes8 bytes
Flow controlHaan (receive window)Nahi
Congestion controlHaan (AIMD)Nahi
SpeedSlower (overhead)Faster
Data boundaryByte-stream (message boundaries preserve nahi hote)Message/datagram oriented (boundaries preserve)
Broadcast/multicastNahi (point-to-point only)Haan
Use casesWeb, email, file transfer, SSH, DBDNS, DHCP, VoIP, gaming, streaming, QUIC

Follow-up jo aata hai: "Video streaming TCP use karta hai ya UDP?" → Live/real-time (video call, gaming) UDP; on-demand streaming (YouTube, Netflix) actually TCP/HTTP (DASH) use karta hai kyunki buffering se latency chal jaati hai aur firewalls TCP ko allow karte hain.

7.5 Socket programming ka essence

TCP (connection-oriented)
Server:
socket() → bind() → listen()
        → accept()  ← blocks
        → recv()/send() → close()

Client:
socket() → connect()
        → send()/recv() → close()
UDP (connectionless)
Server:
socket() → bind()
        → recvfrom() / sendto()
        → close()

Client:
socket()
        → sendto() / recvfrom()
        → close()
  • accept() ek naya connection socket return karta hai — listening socket alag rehta hai. Isliye server multiple clients handle kar sakta hai (thread/process per connection ya epoll).
  • UDP mein har datagram ke saath destination address dena padta hai (sendto), kyunki connection hi nahi hai.
  • Byte order: network big-endian (Network Byte Order) use karta hai. Isliye htons(), htonl(), ntohs(), ntohl() se convert karna padta hai — warna x86 (little-endian) pe port number ulta chala jayega.
08 · transport layer

Reliable Data Transfer: Stop-and-Wait, GBN, Selective Repeat

Ye theory TCP ki neev hai. Window size ke sawaal exams mein pakke aate hain.

08162431

8.1 Problem statement

Neeche wala channel unreliable hai (bits flip ho sakte hain, packets lost ho sakte hain). Upar wali app ko reliable channel chahiye. Beech mein reliable data transfer (rdt) protocol banate hain — step by step.

ProtocolChannel assumptionNaya mechanism
rdt1.0Perfectly reliableKuch nahi chahiye
rdt2.0Bit errors ho sakte hainChecksum + ACK/NAK (ARQ — Automatic Repeat reQuest)
rdt2.1ACK/NAK bhi corrupt ho sakte hainSequence numbers (0,1) — duplicate pakadne ke liye
rdt2.2SameNAK hataya — sirf ACK with seq# (duplicate ACK = NAK ka kaam)
rdt3.0Errors + lossTimer / timeout + retransmission
rdt2.0 ka fatal flaw (poochha jaata hai)

Agar ACK/NAK khud corrupt ho jaye to sender ko pata hi nahi chalega ki receiver ne kya kaha. Agar wo blindly retransmit kare to duplicate ban sakta hai. Solution: har packet pe sequence number lagao — receiver duplicate ko pehchaan ke discard kar dega. Stop-and-wait ke liye sirf 1 bit (0/1) kaafi hai.

rdt3.0 = "alternating bit protocol"

Sender packet bhejta hai, timer start karta hai. ACK aaya → next packet. Timeout hua → retransmit. Premature timeout se duplicate ban sakta hai, par sequence number usse handle kar leta hai. Ye stop-and-wait protocol hai — correct hai, par performance bekaar.

8.2 Stop-and-Wait ki performance problem ★★★ asked a lot

Sender utilization Usender = (L/R) / (RTT + L/R)
Effective throughput = U × R
Q1. 1 Gbps link, 15 ms one-way propagation delay, 8000-bit packet. Utilization aur throughput nikalo.super classic

dtrans = L/R = 8000 bits / 109 bps = 8 μs

RTT = 2 × 15 ms = 30 ms

U = 0.008 ms / (30 + 0.008) ms = 0.008/30.008 = 0.00027 = 0.027%

Throughput = 0.00027 × 1 Gbps ≈ 267 kbps — 1 Gbps ki link pe!

Iska matlab: 30 ms mein sirf 8 μs data bheja, baaki poora time ACK ka intezaar. Protocol ne physical link ki kaabiliyat barbaad kar di. Solution = pipelining.

8.3 Pipelining: Go-Back-N aur Selective Repeat ★★★ asked a lot

Idea: ACK ka wait kiye bina ek saath N packets "in-flight" bhejo. Iske liye chahiye: (1) bada sequence number space, (2) sender/receiver pe buffering, (3) window management.

Pipelined utilization U = N × (L/R) / (RTT + L/R)   (jab tak ye 1 se kam hai)
Ideal window size (link saturate karne ke liye): N ≥ (RTT + L/R) / (L/R)
Go-Back-N (GBN)Selective Repeat (SR)
Receiver bufferNahi — out-of-order packets discardHaan — out-of-order buffer karta hai
ACK typeCumulative ACK (ACK n = "n tak sab mil gaya")Individual ACK har packet ke liye
TimerEk timer (oldest unACKed packet ka)Har unACKed packet ka apna timer
Loss pe kyaUs packet se aage saare retransmitSirf wo packet retransmit
ComplexitySimple receiverComplex (dono taraf buffer + timers)
Bandwidth efficiencyKam (extra retransmissions)Zyada
Window sizes (k-bit seq#)SWS ≤ 2k − 1, RWS = 1SWS = RWS ≤ 2k−1 (yaani 2k/2)
Window size constraints — ye derive karke samjho, ratt ke mat jao

GBN: N ≤ 2k − 1. Agar N = 2k hota, to socho k=2 (seq 0,1,2,3), N=4. Sender 0,1,2,3 bhejta hai. Saare ACK lost ho jaate hain. Receiver ab 4,5,6,7 (yaani 0,1,2,3) ki ummeed kar raha hai. Sender timeout pe purane 0,1,2,3 dobara bhejta hai — receiver unhe naye packets samajh lega! Isliye ek extra "gap" chahiye → N ≤ 2k−1.

SR: N ≤ 2k−1. SR mein receiver window bhi N size ka hai. Sender aur receiver ki windows itni aage-peeche ho sakti hain ki purane aur naye packets ke seq# overlap kar jayein. Windows ko kabhi overlap na karne dene ke liye seq space kam se kam 2N hona chahiye → N ≤ 2k/2.

Q2. 3-bit sequence numbers hain. GBN aur SR mein maximum window size kya hogi?exam favourite

k = 3 → sequence numbers 0 se 7 (total 23 = 8).

GBN: N ≤ 23 − 1 = 7

SR: N ≤ 23−1 = 4 (sender window = receiver window = 4)

Q3. SR ka "dilemma" example samjhao — window size 3 aur seq numbers 0–3 (2-bit) hone pe kya galat hoga?conceptual

Scenario A: Sender 0,1,2 bhejta hai. Receiver teeno le leta hai, ACK bhejta hai, apni window ko 3,0,1 pe shift kar deta hai. Saare ACK lost ho jaate hain. Sender timeout pe packet 0 retransmit karta hai. Receiver ki window mein 0 hai (naye 0 ke roop mein!) → wo purane duplicate 0 ko naya packet samajh ke accept kar lega. Data corrupt.

Scenario B: Sender 0,1,2 bhejta hai. Packet 0 lost. Receiver 1,2 buffer karta hai... — bilkul same packets receiver ko dikh rahe hain dono scenarios mein, par unka matlab alag hai. Receiver distinguish nahi kar sakta.

Fix: window size ≤ seq space / 2 = 4/2 = 2. Tab windows kabhi overlap nahi karengi.

Q4. 10 Mbps link, RTT = 50 ms (propagation), packet 1000 bytes. Link ko 100% utilize karne ke liye window size kitni chahiye? Isko GBN mein kitne bits ke seq# chahiye?numerical

L/R = 8000 bits / 107 bps = 0.8 ms

N ≥ (RTT + L/R)/(L/R) = (50 + 0.8)/0.8 = 63.5 → N = 64 packets

GBN ke liye: N ≤ 2k − 1 → 64 ≤ 2k − 1 → 2k ≥ 65 → k = 7 bits (128 sequence numbers).

Yehi cheez TCP mein "bandwidth-delay product" kehlati hai: BDP = R × RTT = 10 Mbps × 50 ms = 500,000 bits = 62.5 KB. Utna data "pipe mein" ho sakta hai.

Interview mein kya bolna hai — Sections 07–08
  • Mux/demux: UDP 2-tuple, TCP 4-tuple. Isi wajah se ek server port pe hazaron connections chal sakti hain.
  • UDP: 8-byte header, no handshake/state/congestion control → fast, DNS/VoIP/gaming/QUIC ke liye.
  • Stop-and-wait ki utilization = (L/R)/(RTT+L/R) — high-speed link pe bekaar → pipelining chahiye.
  • GBN: cumulative ACK, ek timer, loss pe sab dobara. SR: individual ACK, per-packet timer, sirf lost wala dobara.
  • Window limits: GBN 2k−1, SR 2k−1.
09 · transport layer

TCP deep dive

Agar sirf ek section padhna ho, to ye. Har interviewer TCP ghumaa-firaake poochhta hai.

08162431

9.1 TCP ke characteristics (ek saans mein bolna aana chahiye)

Point-to-point (1 sender, 1 receiver) Reliable, in-order byte stream Full duplex Connection-oriented (handshake) Pipelined (window-based) Flow controlled Congestion controlled

"Byte stream" ka matlab: TCP message boundaries preserve nahi karta. Agar tum 3 baar send() karo 100-100 bytes, receiver ko ek hi recv() mein 300 bytes mil sakte hain, ya 5 tukdon mein. Isliye application ko khud message framing karni padti hai (length prefix ya delimiter). Ye interview mein bahut poochha jaata hai.

9.2 TCP segment structure ★★★ asked a lot

  0                   8                  16                  24                31
 ┌───────────────────────────────────────┬───────────────────────────────────────┐
 │         Source port (16)              │        Destination port (16)          │
 ├───────────────────────────────────────┴───────────────────────────────────────┤
 │                        Sequence number (32)                                  │
 ├───────────────────────────────────────────────────────────────────────────────┤
 │                     Acknowledgement number (32)                              │
 ├──────┬──────────┬─────────────────────┬───────────────────────────────────────┤
 │Hdr   │ unused   │ U A P R S F         │       Receive window (16)              │
 │len(4)│          │ R C S S Y I         │       (flow control ke liye)          │
 │      │          │ G K H T N N         │                                       │
 ├──────┴──────────┴─────────────────────┼───────────────────────────────────────┤
 │        Checksum (16)                   │      Urgent data pointer (16)         │
 ├───────────────────────────────────────┴───────────────────────────────────────┤
 │                  Options (variable: MSS, window scale, SACK, timestamp)       │
 ├───────────────────────────────────────────────────────────────────────────────┤
 │                          Application data                                    │
 └───────────────────────────────────────────────────────────────────────────────┘
    
FieldKaam
Sequence numberIs segment ke pehle byte ka byte-stream number (packet number NAHI!)
ACK numberAgla expected byte ka number (cumulative ACK)
Header length4 bits, 32-bit words mein → header 20 se 60 bytes
SYNConnection establish request (sequence number sync)
ACKACK number field valid hai
FINSender ka data khatam, connection close karna hai
RSTConnection reset/abort (galat port pe aaya, ya error)
PSHReceiver turant application ko de de (buffer mat karo)
URGUrgent data hai (practically use nahi hota)
Receive windowReceiver ke buffer mein kitni jagah khaali hai → flow control
ChecksumHeader + data + pseudo-header pe error detection

9.3 Sequence aur ACK numbers ★★★ asked a lot

Do rule

Seq # = segment ke data ke first byte ka byte-stream position.
ACK # = "mujhe iske pehle tak sab mil gaya, ab ye byte chahiye" — yaani next expected byte. Cumulative hai.

 Telnet example — A "C" character type karta hai (echo back hota hai)

 Host A                                        Host B
   │   Seq=42, ACK=79, data='C'                  │
   │ ───────────────────────────────────────────►│   B ko 1 byte mila (42)
   │                                             │   ab B ko 43 chahiye
   │   Seq=79, ACK=43, data='C' (echo)          │
   │◄─────────────────────────────────────────── │
   │   Seq=43, ACK=80                           │
   │ ───────────────────────────────────────────►│
    
Q1. Host A ne Seq=1000 se 500 bytes bheje. Agla segment ka Seq kya hoga? B ka ACK kya hoga? Agar B khud 200 bytes bheje to uske fields?must know

A ka pehla segment: Seq = 1000, 500 bytes data (bytes 1000–1499).

A ka agla segment: Seq = 1000 + 500 = 1500.

B ka ACK: ACK = 1500 ("1499 tak mil gaya, ab 1500 do").

B apna data bhejta hai: Seq = B ka apna byte stream number (maano 5000), ACK = 1500, 200 bytes. Kyunki TCP full duplex hai — ek hi segment mein apna data bhi aur doosre ka ACK bhi ja sakta hai. Isko piggybacking kehte hain.

9.4 Three-way handshake ★★★ asked a lot

 Client                                                Server
   │                                        (LISTEN)     │
   │  1. SYN=1, Seq=x                                    │
   │ ───────────────────────────────────────────────────►│
   │                                    (SYN_RCVD)       │
   │  2. SYN=1, ACK=1, Seq=y, Ack=x+1                  │
   │◄─────────────────────────────────────────────────── │
   │ (ESTABLISHED)                                       │
   │  3. ACK=1, Seq=x+1, Ack=y+1   (data ja sakta hai)  │
   │ ───────────────────────────────────────────────────►│
   │                                    (ESTABLISHED)    │
    
2-way handshake kyun kaafi nahi? — poochha jaata hai

Do reasons:

  1. Dono taraf ke sequence numbers sync hone chahiye. Connection full-duplex hai, to client ka ISN bhi aur server ka ISN bhi ek doosre ko pata hona chahiye aur dono ko confirm hona chahiye ki doosre ko mila. 2-way mein server ke ISN ka acknowledgement nahi hota.
  2. Half-open connections / purane duplicate SYN. Network mein ek purana SYN atka hua tha aur baad mein pahunch gaya — 2-way mein server ek connection khol ke resources allocate kar dega jo kabhi use hi nahi hogi. Teesra ACK server ko confirm karta hai ki client abhi bhi zinda hai aur wo connection chahta hai.

ISN random kyun? Security — agar predictable ho to attacker connection hijack/spoof kar sakta hai.

9.5 Connection termination — 4-way handshake

 Client                                                Server
   │  1. FIN, Seq=x                                     │
   │ ───────────────────────────────────────────────────►│  (CLOSE_WAIT)
   │  2. ACK, Ack=x+1                                    │
   │◄─────────────────────────────────────────────────── │  server abhi bhi
   │  (FIN_WAIT_2)          [server bacha data bhej sakta hai — half close]
   │  3. FIN, Seq=y                                     │  (LAST_ACK)
   │◄─────────────────────────────────────────────────── │
   │  4. ACK, Ack=y+1                                    │
   │ ───────────────────────────────────────────────────►│  (CLOSED)
   │  (TIME_WAIT — 2×MSL wait, phir CLOSED)              │
    
Do sawaal jo pakke aate hain

Q: Close mein 4 steps kyun jab open mein 3? → Connection full-duplex hai, har direction alag se band hoti hai. Open mein server ka SYN aur ACK ek saath ja sakte the (kyunki dono turant ready the). Close mein server ka ACK turant jaata hai, par uska FIN tab jaayega jab uska bacha data bhej diya ho — isliye alag-alag.

Q: TIME_WAIT kyun (2×MSL, ~2×30s–2×120s)? → (1) Agar aakhri ACK lost ho jaye, server FIN retransmit karega — client ko zinda rehna padega usko dobara ACK karne ke liye. (2) Network mein ghoom rahe purane duplicate segments expire ho jayein, taaki wo agli connection (same 4-tuple) mein na aa jayein.

Practical follow-up

Server pe hazaron TIME_WAIT sockets dikhein to matlab server hi connections close kar raha hai. Isliye web servers keep-alive use karte hain, aur SO_REUSEADDR / tuning karte hain. Interview mein ye bolna real-world knowledge dikhata hai.

9.6 TCP timeout aur RTT estimation ★★ common

Timeout kitna rakhein? RTT se bada hona chahiye — par RTT to badalta rehta hai. Bahut chhota → faltu retransmission. Bahut bada → loss recover karne mein der.

Teen formulas — exam mein direct aate hain EstimatedRTT = (1 − α) · EstimatedRTT + α · SampleRTT   (typical α = 0.125)
DevRTT = (1 − β) · DevRTT + β · |SampleRTT − EstimatedRTT|   (typical β = 0.25)
TimeoutInterval = EstimatedRTT + 4 · DevRTT
  • Ye EWMA (exponentially weighted moving average) hai — purane samples ka weight exponentially girta hai.
  • Karn's algorithm: retransmitted segment ka SampleRTT mat lo (pata nahi chalega ki ACK original ka tha ya retransmission ka). Aur har timeout pe timeout value double kar do (exponential backoff).
  • DevRTT "safety margin" hai — RTT jitna zyada fluctuate karega, margin utna bada.
Q2. Teen RTT samples: 150, 200, 210 ms. EstimatedRTT ka initial value = 150 ms, α = 0.125, β = 0.25, DevRTT initial = 0. Teesre sample ke baad TimeoutInterval nikalo.numerical

Sample 1 = 150: Est = 0.875(150) + 0.125(150) = 150; Dev = 0.75(0) + 0.25|150−150| = 0

Sample 2 = 200: Est = 0.875(150) + 0.125(200) = 131.25 + 25 = 156.25
Dev = 0.75(0) + 0.25|200 − 150| = 0 + 12.5 = 12.5
(Dev ke formula mein hamesha purana EstimatedRTT use karo, ya jo convention course follow kare — consistent raho.)

Sample 3 = 210: Est = 0.875(156.25) + 0.125(210) = 136.72 + 26.25 = 162.97 ms
Dev = 0.75(12.5) + 0.25|210 − 156.25| = 9.375 + 13.44 = 22.81 ms

TimeoutInterval = 162.97 + 4(22.81) = 162.97 + 91.25 = ≈ 254.2 ms

9.7 Fast retransmit

Timeout ka wait lamba hota hai. Lekin agar sender ko 3 duplicate ACKs mil jaayein (yaani 4 baar same ACK number), to iska matlab uske baad ke segments to pahunch rahe hain, sirf ek beech wala gaayab hai. To timeout ka intezaar mat karo — turant retransmit karo.

 Sender bhejta hai: seg1(Seq=100) seg2(200) seg3(300) seg4(400) seg5(500)
 seg2 LOST.
 Receiver: seg1 aaya → ACK 200
           seg3 aaya (out of order) → ACK 200   ← dup 1
           seg4 aaya → ACK 200                  ← dup 2
           seg5 aaya → ACK 200                  ← dup 3
 Sender: 3 dup ACKs mile → turant seg2 retransmit (timeout se pehle)
    

9.8 TCP: GBN hai ya Selective Repeat? ★★ common

Answer: hybrid hai
  • GBN jaisa: cumulative ACKs use karta hai, aur ek hi timer rakhta hai (oldest unACKed segment ke liye).
  • SR jaisa: timeout pe sirf ek segment retransmit karta hai (poori window nahi), aur receiver out-of-order segments ko buffer kar leta hai (discard nahi karta).
  • SACK option (Selective Acknowledgement) ke saath to wo aur bhi SR ban jaata hai — receiver batata hai exactly kaunse blocks mile hain.

Interview line: "TCP is best described as a hybrid of GBN and SR — cumulative ACKs like GBN, but single-segment retransmission and receiver buffering like SR."

9.9 Flow control ★★★ asked a lot

Definition

Flow control = sender ko itna tez bhejne se rokna ki receiver ka buffer overflow ho jaye. Ye ek speed-matching service hai (sender ki rate ↔ receiver ki reading rate).

Receive window rwnd = RcvBuffer − (LastByteRcvd − LastByteRead)
Sender rule: LastByteSent − LastByteAcked ≤ rwnd
  • Receiver har ACK ke saath apna current rwnd header mein bhejta hai.
  • Zero window problem: agar rwnd = 0 ho jaye to sender ruk jaata hai — par phir receiver ko naya rwnd batane ka mauka kaise mile (kyunki ACK data ke saath jaata hai)? Solution: sender chhote window probe segments (1 byte) bhejta rehta hai jab tak window khule nahi.
Flow control vs Congestion control — ye difference must aata hai
Flow controlCongestion control
Kise bachata haiReceiver ko overflow seNetwork (routers) ko overload se
ScopeEnd-to-end, do hosts ke beechPoore network ka concern
Mechanismrwnd — receiver batata haicwnd — sender khud infer karta hai (loss/delay se)
SignalExplicit (header field)Implicit (packet loss, duplicate ACK, timeout)

Aur final sending limit: LastByteSent − LastByteAcked ≤ min(cwnd, rwnd)

9.10 Useful TCP options

  • MSS (Maximum Segment Size) — ek segment mein max application data. Typically 1460 bytes (1500 MTU − 20 IP − 20 TCP). SYN mein negotiate hota hai.
  • Window scaling — 16-bit window field max 65,535 bytes deta hai, jo high-BDP links ke liye kam hai. Scale factor se window 1 GB tak ja sakta hai.
  • SACK — receiver exactly bata deta hai kaunse byte-ranges mile.
  • Timestamps — better RTT measurement + PAWS (wrapped sequence numbers se bachav).
  • Nagle's algorithm — chhote-chhote packets ko jama karke bhejta hai (network efficiency), par latency badhati hai → interactive apps TCP_NODELAY set karti hain.
  • Delayed ACK — receiver 500 ms tak (ya 2nd segment tak) ACK rokta hai taaki piggyback ho sake.

9.11 SYN flood attack (security round mein)

Attacker bahut saare SYN bhejta hai par kabhi teesra ACK nahi bhejta. Server har SYN pe resources allocate karke half-open connection table bhar leta hai → legit users ko jagah nahi milti. Fix: SYN cookies — server state allocate hi nahi karta; wo ISN mein ek cryptographic hash encode kar deta hai, aur jab client ka ACK aata hai tab hash verify karke connection banata hai.

Q3. TCP connection mein Host A ne Seq=200 ka segment (100 bytes) bheja aur wo lost ho gaya, par uske baad ke 2 segments pahunch gaye. Receiver kya ACK bhejega? Sender kya karega?conceptual

Receiver ke paas byte 200–299 nahi hain. Wo out-of-order segments (300–399, 400–499) ko buffer kar lega, par ACK hamesha 200 hi bhejega ("mujhe 200 chahiye") — kyunki ACK cumulative hai.

Sender ko duplicate ACK 200 milte rahenge. 3 duplicate ACKs pe wo fast retransmit kar dega (timeout ka wait nahi karega). Retransmission ke baad receiver ke paas sab kuch aa jayega, to wo seedha ACK 500 bhej dega (cumulative — ek hi ACK mein sab cover).

Q4. "TCP reliable hai" — exactly kaun-kaun se mechanisms milke reliability dete hain?★★★ asked a lot
  1. Sequence numbers — ordering aur duplicate detection.
  2. Cumulative ACKs — receiver confirm karta hai kya mila.
  3. Checksum — corrupted segment discard.
  4. Timeout + retransmission — lost segment dobara.
  5. Fast retransmit (3 dup ACKs) — jaldi recovery.
  6. Receiver buffering + reordering — out-of-order segments sambhal ke, app ko in-order.
  7. Flow control — receiver overflow nahi hota (warna data waise hi drop hota).
  8. 3-way handshake / FIN handshake — connection ki shuruaat aur ant reliable.
Interview mein kya bolna hai — Section 09
  • Seq# = first byte ka number; ACK# = next expected byte (cumulative).
  • 3-way handshake: SYN → SYN-ACK → ACK. 2-way isliye nahi kyunki dono ke ISN confirm hone chahiye aur purane duplicate SYN se half-open connection ban jaati.
  • 4-way close + TIME_WAIT (2 MSL) — last ACK loss aur purane duplicates ke liye.
  • Timeout = EstimatedRTT + 4·DevRTT, Karn's algorithm + exponential backoff.
  • TCP = GBN + SR hybrid.
  • Flow control (rwnd, receiver) ≠ congestion control (cwnd, network). Sending limit = min(cwnd, rwnd).
10 · transport layer

Congestion control — Tahoe, Reno, AIMD

Numerical yahin se banta hai: "cwnd kis round mein kitna hoga". Ek baar samajh gaye to free marks.

08162431

10.1 Congestion kya hai

Definition

Bahut saare sources network mein itna data bhej rahe hain ki network sambhal nahi pa raha. Nateeja: router buffers bharte hain → lambi queuing delay aur packet loss.

Flow control se alag hai — wahan ek receiver dheema tha; yahan network hi choked hai.

Congestion ki "costs" (Kurose ke 3 scenarios ka nichod)

  1. Scenario 1 (infinite buffer, 1 router): jaise-jaise sending rate capacity R/2 ke paas jaata hai, delay infinite hone lagta hai. Throughput to R/2 tak hi ja sakta hai.
  2. Scenario 2 (finite buffer): loss hone lagta hai → sender ko retransmit karna padta hai → "goodput" (useful throughput) sending rate se kam ho jaata hai. Premature timeout se unneeded duplicates bhi bante hain, jo aur capacity khaate hain.
  3. Scenario 3 (multi-hop): jab ek packet upstream links par bandwidth kha ke aage jaake drop ho jaata hai, to us packet pe kharch ki gayi saari upstream capacity waste ho gayi. Isliye congestion collapse itna bura hota hai.

10.2 Congestion control ke do approach

End-to-end (TCP ka tareeka)

Network se koi explicit feedback nahi. Sender khud infer karta hai congestion ko — packet loss (timeout ya 3 dup ACK) aur delay se. Internet mein yehi use hota hai.

Network-assisted

Routers explicitly batate hain. Jaise ECN (Explicit Congestion Notification) — router IP header mein bit set karta hai; receiver TCP ACK mein ECE flag se sender ko batata hai. ATM ke ABR mein choke packets/RM cells.

10.3 TCP congestion control ka core ★★★ asked a lot

Sender ka rule LastByteSent − LastByteAcked ≤ min(cwnd, rwnd)
Sending rate ≈ cwnd / RTT   bytes/sec

cwnd (congestion window) sender khud maintain karta hai. Do phases hain:

PhaseKabcwnd kaise badhta haiGrowth
Slow Startcwnd < ssthreshHar ACK pe cwnd += 1 MSS → har RTT mein cwnd doubleExponential
Congestion Avoidancecwnd ≥ ssthreshHar RTT mein cwnd += 1 MSS (har ACK pe MSS×MSS/cwnd)Linear (additive increase)
"Slow start" naam confusing hai

Slow start actually exponentially tez badhta hai! "Slow" isliye kaha kyunki wo cwnd = 1 MSS se shuru hota hai — yaani shuruat dheemi hai, growth nahi. Ye clarification interview mein achha lagta hai.

10.4 Loss detect hone pe kya hota hai — Tahoe vs Reno ★★★ asked a lot

EventTCP TahoeTCP Reno
Timeoutssthresh = cwnd/2; cwnd = 1 MSS; slow startssthresh = cwnd/2; cwnd = 1 MSS; slow start
3 duplicate ACKsssthresh = cwnd/2; cwnd = 1 MSS; slow start (same as timeout)ssthresh = cwnd/2; cwnd = ssthresh (+3); fast recovery → seedha congestion avoidance
PhilosophyHar loss ko barabar bura maanta hai3 dup ACK matlab network abhi bhi deliver kar raha hai (mild congestion) → itna panic mat karo

TCP NewReno partial ACKs ko better handle karta hai (ek window mein multiple losses). TCP SACK selective ACK use karta hai. Aaj Linux ka default CUBIC hai.

 cwnd
  │        Tahoe: dup ACK pe bhi 1 tak gir jaata hai
 24│      ╱|
 20│    ╱  |         Reno: dup ACK pe aadha (fast recovery)
 16│  ╱    |       ╱‾‾‾╲          ╱‾‾╲
 12│╱      |     ╱      ╲___    ╱     ╲___
  8│       |   ╱                         ← "sawtooth" pattern
  4│       | ╱
  1│_______|╱________________________________
   └───────────────────────────────────────── time (RTT)
    slow start   CA    loss   CA     loss
    

10.5 AIMD — Additive Increase, Multiplicative Decrease

AIMD hi kyun? (fairness ka proof-idea)

Additive increase: har RTT mein +1 MSS — dhire-dhire bandwidth probe karo.
Multiplicative decrease: loss pe cwnd aadha — congestion se tezi se bhaago.

Do connections ka graph socho (x-axis = connection 1 ka throughput, y-axis = connection 2 ka). AIMD ke saath dono ki state baar-baar equal-share diagonal ki taraf convergence karti hai:

  • Additive increase se dono 45° line ke parallel upar jaate hain (dono ko barabar milta hai).
  • Multiplicative decrease se dono origin ki taraf ek line par aate hain — jo zyada le raha tha, wo zyada chhodta hai.
  • Repeat karne se dono fair share pe converge kar jaate hain. AIAD ya MIMD se ye convergence nahi hoti.
Q1. TCP Tahoe. MSS = 1 KB. Initial cwnd = 1, ssthresh = 8. Round 6 ke end pe timeout hota hai. cwnd ka evolution table banao rounds 1–12 ke liye.super classic
Round (RTT)cwnd (start)PhaseNote
11Slow startcwnd doubles
22Slow start
34Slow start
48SS → CAcwnd = ssthresh(8) → ab linear
59CA+1 per RTT
610CATimeout! ssthresh = 10/2 = 5, cwnd = 1
71Slow start
82Slow start
94Slow start
105SS → CAcwnd 8 nahi hoga — ssthresh 5 pe ruk jayega
116CA
127CA

Dhyaan: round 9 mein cwnd 4 tha, doubling se 8 hota — par ssthresh 5 hai, isliye cwnd 5 pe cap ho jaata hai aur congestion avoidance shuru.

Q2. Same scenario par TCP Reno, aur round 6 mein timeout ke bajaye 3 duplicate ACKs mile. Ab kya hoga?must know

Round 6 mein cwnd = 10, 3 dup ACKs mile:

  • ssthresh = cwnd/2 = 5
  • cwnd = ssthresh = 5 (fast recovery mein cwnd = ssthresh + 3 MSS bhi likha jaata hai; simple exams mein ssthresh maan lo — question ki convention follow karo)
  • Slow start mein nahi jaata — seedha congestion avoidance se continue

Round 7: 6, Round 8: 7, Round 9: 8… linear.

Tahoe se comparison: Tahoe round 7 mein 1 se shuru karta, Reno 5 se — isliye Reno ka throughput kaafi behtar hai.

10.6 TCP throughput

Simple average throughput Average throughput ≈ 0.75 × W / RTT   (W = loss ke waqt ka max window)
Kyunki cwnd W/2 se W tak linearly ghumta hai → average = 0.75W
Macroscopic model (loss rate L ke saath) Throughput ≈ 1.22 × MSS / (RTT × √L)
Ye formula kya batata hai — interview insight

Throughput RTT ke inversely proportional hai. Iska matlab: chhota RTT wala connection zyada bandwidth grab karta hai — isliye TCP long-distance flows ke saath "unfair" hai. Aur high-speed links pe (jahan bahut bada W chahiye) loss rate itni kam chahiye hoti hai ki classic TCP practical nahi rehta — isiliye CUBIC/BBR bane.

10.7 TCP fairness

  • Goal: agar K TCP connections ek bottleneck link R share kar rahi hain, to sabko ~R/K milna chahiye. AIMD isko approximately achieve karta hai.
  • RTT unfairness: chhote RTT wale connections zyada le jaate hain.
  • Parallel connections se cheating: agar ek app 9 parallel TCP connections khole aur doosri 1, to 9 wali ko 9/10 bandwidth mil jayegi. Browsers yahi karte the!
  • UDP fair nahi hai — wo congestion control follow hi nahi karta, isliye TCP flows ko dabaa sakta hai.

10.8 Modern congestion control (bonus)

AlgorithmIdeaKahan
TCP CUBICLoss ke baad window ko cubic function se badhata hai: pehle tezi se Wmax ke paas pahunchta hai, wahan dheere-dheere probe karta hai (plateau), phir aage aggressive. RTT-independent.Linux default
Compound TCPLoss-based + delay-based dono componentsWindows
BBRLoss ko signal nahi maanta! Bottleneck bandwidth (BtlBw) aur round-trip propagation time (RTprop) ka estimate rakhta hai aur rate = BtlBw pe pace karta hai. Isse bufferbloat se bachta hai (queue bharne ka intezaar nahi karta).Google, YouTube
Bufferbloat — ek line

Routers mein bahut bade buffers hone se loss-based TCP tab tak bhejta rehta hai jab tak buffer full na ho — nateeja huge queuing delay (video call lag karta hai jab koi download chal raha ho). BBR isi problem ko address karta hai.

10.9 QUIC — HTTP/3 ka transport ★★ common

  • UDP ke upar banaya gaya application-layer protocol (kernel change nahi karna padta, browser update se deploy ho jaata hai).
  • Reliability, congestion control, flow control — sab QUIC khud implement karta hai (TCP jaisa hi logic).
  • TLS 1.3 built-in — connection setup + security ek hi handshake mein → 1-RTT, aur repeat connection pe 0-RTT. TCP+TLS mein ye 3 RTT tak lagta tha.
  • Per-stream reliability — ek stream ka packet loss doosri streams ko block nahi karta → TCP HOL blocking solved.
  • Connection ID — IP badal jaye (WiFi → mobile data) to bhi connection zinda rehti hai (connection migration).
Q3. Do TCP senders ek 10 Mbps bottleneck share kar rahe hain. Ek ka RTT 20 ms, doosre ka 100 ms. Bandwidth kaise batega aur kyun?conceptual

Throughput ∝ 1/RTT (approx, same loss rate maan kar). Ratio = (1/20) : (1/100) = 5 : 1.

Yaani chhote RTT wala ≈ 8.33 Mbps aur bada RTT wala ≈ 1.67 Mbps le jayega.

Kyun: congestion avoidance mein cwnd har RTT mein 1 MSS badhta hai. Chhote RTT wala apni window zyada tez badhata hai, isliye zyada bandwidth capture kar leta hai. Ye TCP ki known unfairness hai — CUBIC isi ko fix karne ki koshish karta hai (uska growth wall-clock time pe based hai, RTT pe nahi).

Interview mein kya bolna hai — Section 10
  • cwnd = sender ka congestion window; rate ≈ cwnd/RTT; limit = min(cwnd, rwnd).
  • Slow start exponential (per RTT double) jab tak ssthresh; phir congestion avoidance linear (+1 MSS/RTT).
  • Timeout → cwnd = 1 (dono Tahoe aur Reno). 3 dup ACK → Tahoe cwnd = 1, Reno cwnd = ssthresh (fast recovery).
  • AIMD fairness pe converge karta hai; throughput ∝ 1/(RTT√L).
  • QUIC = UDP + TLS1.3 + per-stream reliability → 0/1-RTT setup, no TCP HOL, connection migration.
11 · network layer

IP datagram aur fragmentation

Network layer = host-to-host delivery. Har router ismein involved hota hai.

08162431

11.1 Network layer ke do plane ★★ common

Data plane (per-router, fast)

Local, per-router function. Input port pe aaye datagram ko dekh ke forwarding table se output port pe bhejna. Hardware mein, nanoseconds mein.

Control plane (network-wide, slow)

Poore network ka logic — routing algorithms jo forwarding tables banate hain. Do tareeke: per-router control plane (traditional: har router routing protocol chalata hai) ya SDN (ek logically centralized controller tables install karta hai).

Internet ka service model = "best effort": no guarantee on delivery, ordering, timing, ya bandwidth. Simplicity ki wajah se hi Internet itna scale kar paya — saari complexity edge (hosts) pe daali gayi.

11.2 IPv4 datagram format ★★★ asked a lot

  0        4         8              16                            31
 ┌────────┬─────────┬──────────────┬──────────────────────────────┐
 │Version │ IHL     │ Type of Svc  │      Total Length (16 bits)     │  ← bytes mein, max 65535
 │ (4)    │ (4)     │ (8) / DSCP   │                              │
 ├────────┴─────────┴──────────────┼──────┬───────────────────────┤
 │      Identification (16)          │Flags │  Fragment Offset (13) │  ← fragmentation
 │                                 │ (3)  │  (8-byte units mein)  │
 ├──────────────────┬──────────────┼──────┴───────────────────────┤
 │   TTL (8)        │ Protocol (8) │    Header Checksum (16)      │
 ├──────────────────┴──────────────┴──────────────────────────────┤
 │                    Source IP address (32)                      │
 ├────────────────────────────────────────────────────────────────┤
 │                  Destination IP address (32)                   │
 ├────────────────────────────────────────────────────────────────┤
 │                  Options (variable, 0–40 bytes)                │
 ├────────────────────────────────────────────────────────────────┤
 │                          Data (payload)                        │
 └────────────────────────────────────────────────────────────────┘
    
FieldKaam / yaad rakhne layak baat
Version4 ya 6
IHL (header length)32-bit words mein. Min 5 (= 20 bytes), max 15 (= 60 bytes)
Total LengthHeader + data, bytes mein. Max 65,535 (practically MTU se limited)
IdentificationEk hi original datagram ke saare fragments ka same ID
Flagsbit0 reserved, bit1 = DF (Don't Fragment), bit2 = MF (More Fragments)
Fragment OffsetOriginal datagram mein is fragment ka position, 8-byte units mein (isliye fragment size 8 ka multiple hona chahiye)
TTLHar router pe 1 kam; 0 hone pe drop + ICMP Time Exceeded. Infinite looping se bachav.
ProtocolUpar wali layer ka protocol: 6 = TCP, 17 = UDP, 1 = ICMP, 89 = OSPF
Header checksumSirf header pe (data pe nahi). Har hop pe recompute hota hai kyunki TTL badalta hai. IPv6 mein ye field hata diya gaya.

11.3 IP fragmentation ★★★ asked a lot

Kyun zaroorat padi

Har link ka apna MTU (Maximum Transmission Unit) hota hai — ek frame mein max kitne bytes ja sakte hain (Ethernet: 1500 bytes). Agar datagram MTU se bada hai to router use fragments mein tod deta hai.

Do rules
  1. Reassembly sirf destination host pe hoti hai, beech ke routers pe nahi. (Kyunki fragments alag-alag raaste le sakte hain.)
  2. Har fragment ka payload (last ke alawa) 8 ka multiple hona chahiye, kyunki offset 8-byte units mein count hota hai.
Q1. 4000-byte datagram (20 byte header + 3980 byte data) ko 1500-byte MTU wali link pe bhejna hai. Fragments banao — har ek ka length, ID, offset, flag.super classic

Step 1: Har fragment mein data = MTU − IP header = 1500 − 20 = 1480 bytes. Ye 8 ka multiple hai (1480/8 = 185) ✓

Step 2: 3980 bytes data ko todo: 1480 + 1480 + 1020 = 3980

FragmentTotal lengthData bytesIDOffsetMF flag
115000–1479x01
215001480–2959x185 (=1480/8)1
310402960–3979x370 (=2960/8)0

Verify: teesre fragment ki total length = 1020 data + 20 header = 1040 ✓. Sabki ID same ✓. Aakhri ka MF = 0 ✓.

Interview trick: agar poochha jaye "receiver ko kaise pata chalega ki saare fragments aa gaye?" → offset se position pata chalti hai, MF=0 wala aakhri hai, aur ID se group. Agar ek fragment bhi kho jaye to poora datagram discard ho jaata hai (isliye fragmentation bura hai).

IPv6 mein fragmentation

IPv6 mein routers fragment nahi karte — sirf source host kar sakta hai. Agar packet bada hai to router ICMPv6 "Packet Too Big" bhej deta hai aur source Path MTU Discovery karke chhota bhejta hai. Isse routers ka kaam simple aur fast ho jaata hai.

12 · network layer

IP addressing, subnetting aur CIDR

Sabse zyada numerical yahin se aate hain. Ye section 3 baar padhna, aur khud calculate karna.

08162431

12.1 IP address ka basic

  • 32-bit identifier, dotted-decimal mein likha jaata hai: 223.1.1.1 = 11011111 00000001 00000001 00000001
  • IP address host ka nahi, interface ka hota hai. Router ke har interface ka apna IP hota hai (isliye router ke paas multiple IPs hote hain).
  • Address ke do hisse: Network (prefix) + Host part.

12.2 Classful addressing (purana, par poochha jaata hai)

ClassLeading bitsRange (first octet)Network/Host bitsNetworksHosts per network
A01–1268 / 2427 = 128224 − 2 = 16,777,214
B10128–19116 / 16214 = 16,384216 − 2 = 65,534
C110192–22324 / 822128 − 2 = 254
D1110224–239Multicast
E1111240–255Reserved/experimental

Classful kyun mar gaya: Class B (65k hosts) chhoti company ke liye bahut bada, Class C (254) bahut chhota. Beech ka koi option nahi tha → address space ki barbaadi. Isliye CIDR aaya.

12.3 CIDR aur subnet mask ★★★ asked a lot

CIDR = Classless Inter-Domain Routing

Format: a.b.c.d/x — jahan x = network prefix ke bits ki sankhya. Baaki (32 − x) bits host ke.

200.23.16.0/23 → pehle 23 bits network, baaki 9 bits host.

Char formulas — inhi se saare sawaal bante hain Total addresses = 2(32 − x)
Usable hosts = 2(32 − x) − 2  (−2: network address aur broadcast address)
Network address = IP AND subnet mask  (host bits sab 0)
Broadcast address = network address with host bits sab 1
Block size (increment) = 256 − (mask ka last non-255 octet)
CIDRSubnet maskTotal addressesUsable hostsBlock size
/24255.255.255.0256254256
/25255.255.255.128128126128
/26255.255.255.192646264
/27255.255.255.224323032
/28255.255.255.240161416
/29255.255.255.248868
/30255.255.255.252424
/16255.255.0.065,53665,534—

Yaad rakhne ka trick: mask ke octet values hamesha inhi mein se hoti hain — 128, 192, 224, 240, 248, 252, 254, 255 (har baar aadha).

12.4 Special addresses

AddressMatlab
0.0.0.0/8"This network" / unspecified (DHCP se pehle)
127.0.0.0/8Loopback — 127.0.0.1 = localhost. Packet host se bahar jaata hi nahi.
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16Private addresses (RFC 1918) — Internet pe route nahi hote, NAT ke peeche use hote hain
169.254.0.0/16APIPA / link-local — jab DHCP fail ho jaye
255.255.255.255Limited broadcast (subnet ke bahar nahi jaata)
224.0.0.0/4Multicast

12.5 Subnetting — step by step

Q1. Ek organization ko block 17.12.14.0/26 mila hai. (a) Kitne addresses? (b) Network address? (c) Broadcast address? (d) Usable host range?must know

(a) 232−26 = 26 = 64 addresses, usable hosts = 62.

(b) Network address: mask = 255.255.255.192. Last octet: 14 AND 192.
14 = 00001110, 192 = 11000000 → AND = 00000000 = 0
Network address = 17.12.14.0

(c) Broadcast: host bits sab 1 → last octet = 00111111 = 63 → 17.12.14.63

(d) Usable range: 17.12.14.1 se 17.12.14.62

Shortcut: block size = 256 − 192 = 64. To blocks hain: .0–.63, .64–.127, .128–.191, .192–.255. Diya hua IP .14 hai → pehle block mein.

Q2. IP 192.168.10.100/27 diya hai. Network address, broadcast address, aur host range nikalo.practice

Step 1 — block size: /27 → mask 255.255.255.224 → block size = 256 − 224 = 32.

Step 2 — subnets: .0, .32, .64, .96, .128, .160, .192, .224

Step 3 — 100 kis block mein? 96 ≤ 100 < 128 → block .96.

Network address = 192.168.10.96
Broadcast = 192.168.10.127 (96 + 32 − 1)
Usable hosts = 192.168.10.97 – 192.168.10.126 (30 hosts)

Q3. Ek organization ke 3 departments hain jinme 60, 25 aur 10 hosts chahiye. Usko 200.10.20.0/24 mila hai. VLSM se subnet karo.★★ common

Rule: sabse bade requirement se shuru karo (VLSM).

Dept A (60 hosts): chahiye 60 + 2 = 62 → 26 = 64 ≥ 62 → host bits = 6 → /26
→ 200.10.20.0/26   (range .0–.63, hosts .1–.62)

Dept B (25 hosts): chahiye 27 → 25 = 32 → host bits = 5 → /27
→ 200.10.20.64/27   (range .64–.95, hosts .65–.94)

Dept C (10 hosts): chahiye 12 → 24 = 16 → host bits = 4 → /28
→ 200.10.20.96/28   (range .96–.111, hosts .97–.110)

Bacha hua: 200.10.20.112 – 200.10.20.255 (future ya router-to-router /30 links ke liye).

Router-to-router point-to-point link ke liye /30 use hota hai (2 usable hosts) — ye trivia bhi poochha jaata hai. Modern networks /31 bhi use karte hain (RFC 3021).

12.6 Longest Prefix Matching ★★★ asked a lot

Router ki forwarding table mein prefixes hote hain. Agar destination IP ek se zyada entries se match kare, to router sabse lamba (most specific) prefix chunta hai.

Q4. Forwarding table di hai. Batao kaunsa interface use hoga: (a) 11001000 00010111 00010110 10100001 (b) 11001000 00010111 00011000 10101010exam favourite
PrefixInterface
11001000 00010111 00010*** ********0
11001000 00010111 00011000 ********1
11001000 00010111 00011*** ********2
otherwise3

(a) …00010110… — 3rd octet 00010110. Entry 1 (00010***) match karta hai ✓. Entry 2/3 (00011…) match nahi karte ✗. → Interface 0

(b) …00011000 10101010 — Entry 2 (00011000 ********) match ✓ aur Entry 3 (00011***) bhi match ✓. Entry 2 ka prefix lamba hai (24 bits vs 21 bits) → Interface 1

Kyun LPM: ye CIDR aur route aggregation ko kaam karne deta hai — ISP ek bada block advertise karta hai, aur uske andar ki koi specific organization apna chhota (more specific) prefix advertise kar sakti hai, jo automatically preference paa jaata hai.

12.7 Route aggregation (supernetting)

ISP apne saare customers ke prefixes ko ek bade prefix mein "jodh" ke advertise karta hai — isse global routing tables chhoti rehti hain.

Q5. Char blocks hain: 200.10.4.0/24, 200.10.5.0/24, 200.10.6.0/24, 200.10.7.0/24. Inko ek prefix mein aggregate karo.practice

Third octet binary mein likho:

4 = 00000100
5 = 00000101
6 = 00000110
7 = 00000111
     ↑ common 6 bits

Pehle 16 bits (200.10) common hain + third octet ke pehle 6 bits common → total 22 bits common.

Aggregate = 200.10.4.0/22 (covers 200.10.4.0 – 200.10.7.255 = 1024 addresses)

Interview mein kya bolna hai — Sections 11–12
  • IP header: TTL, Protocol (6=TCP, 17=UDP), Identification/Flags/Offset (fragmentation), 20-byte min.
  • Fragmentation MTU ki wajah se, reassembly sirf destination pe, offset 8-byte units mein.
  • CIDR /x → hosts = 232−x − 2; network = IP AND mask; broadcast = host bits all 1.
  • VLSM: sabse badi requirement pehle allocate karo.
  • Longest prefix match forwarding — most specific route jeetti hai.
13 · network layer

DHCP, NAT, ICMP aur IPv6

Ghar ke router mein ye chaaron roz chal rahe hain. Interview mein DHCP aur NAT pakke aate hain.

08162431

13.1 DHCP — IP address milta kaise hai ★★★ asked a lot

Do sawaal alag hain: (1) network ko block kaise milta hai → ISP se, jo aage ICANN/RIR se leta hai. (2) host ko address kaise milta hai → manually (static) ya DHCP se ("plug-and-play protocol").

DORA — chaar steps
  1. DISCOVER — client broadcast karta hai (src 0.0.0.0:68 → dst 255.255.255.255:67) "koi DHCP server hai?"
  2. OFFER — server broadcast se ek IP offer karta hai (transaction ID same rakh ke)
  3. REQUEST — client ek offer choose karke formally maangta hai (broadcast, taaki baaki servers ko pata chale)
  4. ACK — server confirm karta hai, lease time ke saath

DHCP sirf IP address nahi deta — ye bhi deta hai: subnet mask, default gateway (first-hop router) ka IP, aur local DNS server ka IP. Ye 4 cheezein interview mein poochhi jaati hain.

  • UDP pe chalta hai, port 67 (server) / 68 (client).
  • Broadcast kyun? Kyunki client ke paas abhi apna IP hi nahi hai aur server ka pata bhi nahi.
  • Lease hoti hai — time khatam hone se pehle renew karna padta hai, warna address wapas pool mein.
  • Agar DHCP server doosre subnet mein ho to DHCP relay agent router pe chahiye.

13.2 NAT — Network Address Translation ★★★ asked a lot

Idea

Poore local network ke liye bahar ki duniya ko ek hi public IP dikhta hai. Andar sab private addresses (192.168.x.x) use karte hain. Router beech mein baithke address+port ko translate karta hai.

 Local network (private)                    NAT router                 Internet
 ┌─────────────────────┐            ┌────────────────────┐
 │ 10.0.0.1:3345 ──────┼───────────►│ WAN IP 138.76.29.7 │──────► 128.119.40.186:80
 │                     │            │ port 5001           │
 │ 10.0.0.2:3345 ──────┼───────────►│ port 5002           │──────►
 └─────────────────────┘            └────────────────────┘

 NAT translation table
 ┌──────────────────────────┬──────────────────────────┐
 │ WAN side (bahar)         │ LAN side (andar)         │
 ├──────────────────────────┼──────────────────────────┤
 │ 138.76.29.7 : 5001       │ 10.0.0.1 : 3345          │
 │ 138.76.29.7 : 5002       │ 10.0.0.2 : 3345          │
 └──────────────────────────┴──────────────────────────┘
    
  1. Outgoing packet: source (10.0.0.1, 3345) → router use (138.76.29.7, 5001) se replace karta hai aur table mein entry banata hai.
  2. Reply aata hai destination (138.76.29.7, 5001) pe.
  3. Router table dekhta hai → destination ko (10.0.0.1, 3345) mein badal ke andar bhej deta hai.
NAT ke faayde
  • Ek public IP se hazaron devices chal jaate hain → IPv4 exhaustion se raahat (16-bit port field → ~60,000 simultaneous connections)
  • ISP badalne pe andar ke addresses badalne nahi padte
  • Andar ke devices bahar se seedhe visible nahi → thodi security (firewall jaisa side effect)
NAT ke nuksaan (controversial kyun hai)
  • Router layer 3 device hai par port numbers (L4) chhed raha hai — layering violation
  • End-to-end principle todta hai
  • NAT traversal problem: bahar se andar wale server tak connection banana mushkil (P2P, gaming, VoIP)
  • Asli solution IPv6 hai, NAT ek jugaad hai

NAT traversal ke solutions: (1) Static port forwarding — router pe manually configure. (2) UPnP / IGD — app khud router se mapping maang leti hai. (3) Relaying (TURN) — beech mein ek public server jisse dono connect karte hain (Skype yahi karta tha). (4) STUN + hole punching — dono side apna mapping seekh ke direct connect karte hain.

13.3 ICMP — network ka "error report" protocol ★★ common

  • Hosts aur routers network-level info exchange karne ke liye use karte hain — error reporting aur diagnostics.
  • ICMP messages IP datagram ke payload mein jaate hain (Protocol number = 1). Isliye ye "IP ke upar" hai, par network layer ka hi hissa maana jaata hai (kyunki ye IP ki service ka part hai, application ka nahi).
  • Har message mein Type + Code hote hain + jis packet se error hua uske header ke pehle 8 bytes.
TypeCodeMatlabKahan dikhta hai
00Echo replyping ka jawab
80Echo requestping
30/1/3Destination network / host / port unreachabletraceroute ka ant
34Fragmentation needed but DF setPath MTU discovery
110TTL expiredtraceroute ka har hop
40Source quench (congestion control) — ab deprecated—
50Redirect — "better route udhar hai"—

13.4 IPv6 ★★ common

Motivation: 32-bit address space khatam ho raha tha. Saath hi header ko simplify karke routers ko fast banana tha.

IPv4IPv6
Address size32 bits (~4.3 billion)128 bits (~3.4×1038)
Header size20–60 bytes (variable)40 bytes fixed
NotationDotted decimalHex, colon-separated: 2001:0db8::1
ChecksumHaan (har hop pe recompute)Nahi — L2 aur L4 already karte hain, speed badhi
FragmentationRouters bhi kar sakte hainSirf source; router ICMPv6 "Packet Too Big" bhejta hai
OptionsHeader ke andarExtension headers (chain mein)
BroadcastHaanNahi — multicast + anycast se kaam
Address configDHCP/manualSLAAC (stateless auto-config) bhi
SecurityOptionalIPsec designed-in
Flow labelNahiHaan (20-bit, same "flow" identify karne ke liye)

IPv4 → IPv6 transition

  • Dual stack — devices dono protocols chalate hain, jahan jo mile use karte hain.
  • Tunneling — IPv6 datagram ko IPv4 datagram ke payload mein daal ke IPv4-only region ke paar bhejna. Doosri taraf tunnel endpoint use nikal leta hai.
 IPv6 host ─── IPv6 net ───[tunnel entry]═══ IPv4 network ═══[tunnel exit]─── IPv6 net ─── IPv6 host
                            IPv6 packet ko            IPv4 header ke andar        IPv6 packet
                            IPv4 me wrap kiya          IPv6 packet safar karta hai  wapas nikala
    
Q1. Tumhara laptop naye WiFi se juda. Pehle 30 seconds mein kaunse network protocols chalte hain aur kis order mein?★★★ asked a lot
  1. 802.11 association — access point se link banti hai (scanning, authentication, association).
  2. DHCP DORA — IP address, subnet mask, default gateway, DNS server ka IP milta hai. (Ye DHCP messages UDP → IP → Ethernet frame mein broadcast MAC FF:FF:FF:FF:FF:FF pe jaate hain.)
  3. ARP — default gateway ka MAC address pata karne ke liye (kyunki frame bhejne ke liye MAC chahiye).
  4. DNS query — jab tum koi site kholte ho (UDP 53, gateway ke through local DNS server tak).
  5. TCP handshake + TLS handshake + HTTP request.

Ye poora sequence Section 22 mein detail mein hai — ye interview ka favourite hai.

Interview mein kya bolna hai — Section 13
  • DHCP = DORA over UDP 67/68, aur IP + mask + gateway + DNS chaaron deta hai.
  • NAT = (private IP, port) ↔ (public IP, port) translation; IPv4 bachaata hai par end-to-end connectivity todta hai.
  • ICMP: type 8/0 = ping, type 11 = TTL expired (traceroute), type 3 = unreachable.
  • IPv6: 128-bit, 40-byte fixed header, no checksum, no router fragmentation; transition dual-stack ya tunneling se.
14 · network layer

Router ke andar kya hota hai

Switching fabric, queuing, aur packet scheduling. College exam mein zyada, interview mein occasionally.

08162431

14.1 Router architecture

        ┌──────────────────────────────────────────────┐
        │  Routing processor (control plane, software)   │  ← routing protocols
        │  routing table banata hai                     │     chalata hai
        └──────────────────────┬───────────────────────┘
                 forwarding table copy ↓
   ┌──────────┐         ┌───────────────────┐         ┌──────────┐
   │ Input    │────────►│  Switching        │────────►│ Output   │
   │ ports    │         │  fabric            │         │ ports    │
   │ L1,L2,    │         │  (memory/bus/     │         │ queue +  │
   │ lookup +  │         │   crossbar)       │         │ L2,L1    │
   │ queue     │         └───────────────────┘         └──────────┘
   └──────────┘
       ← data plane — hardware mein, nanoseconds mein →
    

Input port ka kaam: physical layer termination → link layer processing (decapsulation) → lookup (destination IP se forwarding table mein longest prefix match, aksar TCAM hardware se) → queue → fabric.

14.2 Switching fabric ke 3 tareeke

TypeKaiseLimitation
MemoryPurane routers: packet CPU ke control mein memory mein copy hota hai, phir output port peSpeed = memory bandwidth / 2 (do baar bus cross karta hai)
BusEk shared bus se input se output tak directEk time pe ek hi packet → bus speed hi switching speed
Interconnection network (crossbar)2N buses ka grid; multiple packets parallel mein cross kar sakte hain (agar alag output ports ho)Complex/mehnga, par sabse fast — high-end routers mein multiple planes bhi

14.3 Queuing kahan hoti hai ★★ common

Input queuing + HOL blocking

Agar fabric input ports se dheema hai to input pe queue banti hai. Problem: Head-of-Line blocking — queue ka pehla packet jis output port pe jaana chahta hai wo busy hai, to uske peeche wale packets bhi ruk jaate hain, chahe unka output port free ho.

Output queuing

Agar fabric input links se tez hai to packets output port pe jama hote hain. Yahan buffering chahiye aur agar buffer bhar jaye to packet drop (yahi congestion loss hai). Scheduling yahin hoti hai.

Kitna buffer chahiye Classic rule (RFC 3439): B = RTT × C  (C = link capacity)
N flows ke saath (Appenzeller): B = RTT × C / √N
Bahut bada buffer = bufferbloat (huge delay). Bahut chhota = kam utilization.

14.4 Packet scheduling

DisciplineKaise kaam karta haiProblem
FCFS / FIFOJo pehle aaya wo pehle jayegaKoi differentiation nahi; ek aggressive flow sabko dabaa sakta hai
Priority queuingTraffic classes mein baanto; high-priority queue pehle serve karo (non-preemptive)Starvation — low priority ko kabhi mauka na mile
Round RobinHar class ki queue se baari-baari ek packetSab ko barabar, chahe kisi ko zyada chahiye
Weighted Round Robin / WFQHar class ko weight wi — usko bandwidth ka wi / Σwj hissa milta haiImplementation complex, par QoS ke liye standard
Fair Queuing (bit-by-bit round robin)Har flow ko theoretically ek-ek bit karke serve karo; practically har packet ka finish time nikal ke sabse chhote finish time wala pehle bhejoPer-flow state rakhna padta hai

14.5 AQM aur RED

Problem with drop-tail: buffer full hone tak wait karte ho, phir aane wale saare packets drop — isse (a) queue hamesha full rehti hai (delay zyada), (b) global synchronization — sab TCP flows ek saath backoff karte hain aur ek saath badhte hain, link utilization ghatti-badhti rehti hai.

RED (Random Early Detection)

Buffer full hone se pehle hi, probability ke saath random packets drop (ya ECN mark) karo — taaki kuch flows jaldi slow down ho jaayein aur queue kabhi full na ho.

  • avg = exponentially weighted average queue length (instantaneous nahi — bursts ko allow karne ke liye)
  • avg < minth → koi drop nahi
  • minth ≤ avg < maxth → probability p ke saath drop, jo avg ke saath linearly badhti hai
  • avg ≥ maxth → saare packets drop

Faayde: average queue length chhoti (kam delay), global synchronization se bachav, aur bursty traffic ko accommodate karta hai. Modern versions: CoDel, FQ-CoDel (bufferbloat ke liye).

Q1. Ek router ke 3 flows hain jinke weights 3, 2, 1 hain aur link capacity 12 Mbps hai. WFQ se har flow ko kitna milega? Agar flow 1 sirf 2 Mbps hi bhej raha ho to?numerical

Case 1 — sab backlogged: total weight = 3+2+1 = 6

  • Flow 1: (3/6) × 12 = 6 Mbps
  • Flow 2: (2/6) × 12 = 4 Mbps
  • Flow 3: (1/6) × 12 = 2 Mbps

Case 2 — flow 1 sirf 2 Mbps bhej raha: WFQ work-conserving hai — bachi hui capacity baaki flows mein unke weight ratio mein baant di jaati hai.

  • Flow 1: 2 Mbps (jitna chahiye)
  • Bacha 10 Mbps, flow 2 aur 3 ka ratio 2:1 → Flow 2: 6.67 Mbps, Flow 3: 3.33 Mbps
Interview mein kya bolna hai — Section 14
  • Router = input ports (lookup) + switching fabric (memory/bus/crossbar) + output ports (queue + scheduling), plus routing processor (control plane).
  • Input queuing mein HOL blocking, output queuing mein buffering aur drop.
  • Buffer sizing: RTT×C (ya RTT×C/√N); zyada buffer = bufferbloat.
  • Scheduling: FIFO → priority (starvation) → RR → WFQ (weighted fair share). AQM/RED buffer full hone se pehle drop karke queue chhoti rakhta hai.
15 · control plane

Routing algorithms: Dijkstra aur Distance Vector

Dijkstra tumhe DSA se aata hi hoga — yahan bas network context mein lagana hai. DV mein count-to-infinity important hai.

08162431

15.1 Graph abstraction

Network = graph G = (N, E). Nodes = routers, edges = links, edge cost c(x,y) = link ka cost (delay, 1/bandwidth, ya monetary cost). Goal: har source-destination pair ke liye least cost path.

ClassificationType AType B
InformationGlobal — sab routers ko poora topology pata (Link State)Decentralized — sirf padosiyon ka pata, iterative exchange (Distance Vector)
DynamicsStatic — routes dheere badalte hainDynamic — link cost/topology change pe jaldi adapt
Load sensitivityLoad-sensitive (cost traffic pe depend) — oscillation ka khatraLoad-insensitive (aaj ke RIP/OSPF/BGP)

15.2 Link State routing — Dijkstra ★★★ asked a lot

  • Har router apne links ka status poore network mein broadcast karta hai (link state broadcast/flooding).
  • Sabke paas identical, complete topology map aa jaata hai.
  • Har router khud Dijkstra chalake apna shortest path tree aur forwarding table banata hai.
Complexity Naive: O(n²)  · With min-heap: O(E log n)  · Messages: O(n·E) (broadcast)
Q1. Neeche wale network pe Dijkstra chalao source = u se. Har step ki table banao aur u ki forwarding table nikalo.exam favourite
          5
     u ────────── v
     │ \        / │ \
   1 │  \2    2/  │3  \1
     │   \    /   │    \
     w ─── x ──── y ──── z
        3      1      2

 Edges: u-v=5, u-w=1, u-x=2, v-x=2, v-y=3, v-z=1,
        w-x=3, x-y=1, y-z=2

Notation: D(n) = abhi tak ka best cost, p(n) = predecessor.

StepN′ (settled)D(v),pD(w),pD(x),pD(y),pD(z),p
0u5,u1,u2,u∞∞
1uw5,u—2,u∞∞
2uwx4,x——3,x∞
3uwxy4,x———5,y
4uwxyv————5,y
5uwxyvzdone

Explanation of key steps:

  • Step 1: w add hua (cost 1). w se x ka raasta 1+3 = 4, par direct 2 better hai → x rehta 2,u.
  • Step 2: x add hua. Ab x ke through v = 2+2 = 4 (pehle 5 tha) → update to 4,x. Aur y = 2+1 = 3,x.
  • Step 3: y add hua (3). y se z = 3+2 = 5,y.
  • Step 4: v add hua (4). v se z = 4+1 = 5 — tie hai, koi improvement nahi.

u ki forwarding table (pehla hop nikalne ke liye predecessor chain ulti chalao):

DestinationPathCostOutgoing link
vu→x→v4(u,x)
wu→w1(u,w)
xu→x2(u,x)
yu→x→y3(u,x)
zu→x→y→z5(u,x)
Dijkstra ki oscillation problem

Agar link cost traffic ke hisaab se set ho, to sab routers ek saath "khali" raaste pe shift ho jaate hain → wo bhar jaata hai → agli iteration mein sab wapas shift → route oscillate karte rehte hain. Solutions: link cost ko load-independent rakho, ya routers ke LS advertisement ko de-synchronize karo (random jitter).

15.3 Distance Vector — Bellman-Ford ★★★ asked a lot

Bellman-Ford equation Dx(y) = minv { c(x,v) + Dv(y) }
"x se y tak ka min cost = har padosi v ke liye (x se v ka cost + v se y ka cost) ka minimum"

Algorithm (har node par):

  1. Apna distance vector Dx (har destination ke liye estimate) rakho.
  2. Padosiyon ko apna DV bhejo.
  3. Jab kisi padosi ka DV aaye, Bellman-Ford se apna DV update karo.
  4. Agar apna DV badla → padosiyon ko phir bhejo. Warna chup raho.

Properties: iterative, asynchronous (sab ko step-lock mein chalne ki zaroorat nahi), self-terminating (jab kuch nahi badalta, messages ruk jaate hain), aur distributed.

Q2. Teen nodes x, y, z. c(x,y)=2, c(x,z)=7, c(y,z)=1. Har node ka initial DV likho aur ek round ke exchange ke baad x ka DV nikalo.practice

Initial (sirf direct links pata hain):

D_x = [x:0, y:2, z:7]
D_y = [x:2, y:0, z:1]
D_z = [x:7, y:1, z:0]

x ko y aur z ke DV mile. Bellman-Ford lagao:

Dx(y) = min{ c(x,y) + Dy(y), c(x,z) + Dz(y) } = min{2+0, 7+1} = 2 (via y)

Dx(z) = min{ c(x,y) + Dy(z), c(x,z) + Dz(z) } = min{2+1, 7+0} = 3 (via y!)

Naya D_x = [x:0, y:2, z:3] — direct link 7 tha, par y ke through 3 mila. x ab z ke liye y ko next hop banayega.

15.4 Count-to-infinity problem ★★★ asked a lot

Good news travels fast, bad news travels slow

Cost kam hone ki khabar jaldi phail jaati hai. Cost badhne / link toot-ne ki khabar bahut dheere phailti hai, kyunki nodes ek doosre ki purani (stale) information par bharosa karke ek doosre ko "ghuma" dete hain.

Q3. Count-to-infinity ko example se samjhao aur uske solutions batao.must know
  X ──1── Y ──1── Z

 Normal: D_Y(X)=1, D_Z(X)=2 (via Y)

 Ab X–Y link toot gaya:
 Y sochta hai: "X ko direct nahi ja sakta. Par Z bolta hai uska X tak cost 2 hai!"
   → D_Y(X) = 1 (Y→Z ka cost) + 2 = 3   ← Y ko nahi pata ki Z ka raasta khud Y se hoke jaata hai
 Z ko Y ka naya DV milta hai: D_Z(X) = 1 + 3 = 4
 Y phir: 1 + 4 = 5 … Z: 6 … Y: 7 …
 
 Ye tab tak chalta hai jab tak cost "infinity" (RIP mein 16) na pahunch jaye.

Solutions:

  • Split horizon: Jis padosi se tumne route seekha hai, usi ko wo route wapas mat advertise karo. (Z, Y ko X ka route nahi batayega kyunki wo Y se hi seekha tha.)
  • Split horizon with poisoned reverse: Aur bhi strong — usi padosi ko us route ka cost infinity bata do. ("Z, Y se kehta hai: mera X tak cost ∞ hai.")
  • Define infinity small: RIP mein 16 = infinity — isse loop jaldi khatam hota hai (par network diameter 15 hops tak limit ho jaata hai).
  • Hold-down timers aur triggered updates.

Important limitation: poisoned reverse 3+ nodes ke loop ko poori tarah solve nahi karta. Ye follow-up interview mein poochha jaata hai.

15.5 LS vs DV — comparison table ★★ common

Link State (Dijkstra / OSPF)Distance Vector (Bellman-Ford / RIP)
Kya pata haiPoora topology mapSirf padosiyon se aayi distances
Kise batata haiSabko (flooding) apne links ke baare meinPadosiyon ko poori table ke baare mein
Message complexityO(n·E) — n nodes, E linksSirf padosiyon tak, par convergence time variable
ConvergenceO(n²) computation, deterministicVariable, count-to-infinity ho sakti hai
Robustness (router kharab ho jaye)Router sirf apni link cost galat bolega; nodes independently compute karte hain → error localizedGalat DV padosiyon mein phailta hai, poore network mein propagate
MemoryZyada (poora map)Kam
ScalabilityBade networks mein areas mein todna padta haiChhote networks ke liye theek
16 · control plane

RIP, OSPF, BGP aur SDN

Intra-AS vs Inter-AS. BGP Internet ko jodne wala "glue" hai.

08162431

16.1 Autonomous System (AS) — routing ko do tier mein kyun toda ★★ common

Internet ke crores routers pe ek hi flat routing algorithm nahi chal sakta. Do reason:

  • Scale — 600 million+ destinations ki table aur uske liye link-state broadcast — impossible.
  • Administrative autonomy — har organization apna network apne hisaab se chalana chahti hai, aur apni policy chhupana chahti hai.

Isliye routers ko Autonomous Systems (AS) mein baanta gaya (har AS ka apna ASN number). Do level:

Intra-AS (IGP) — AS ke andar

Goal: performance (shortest/fastest path). Protocols: RIP, OSPF, IS-IS, EIGRP.

Inter-AS (EGP) — AS ke beech

Goal: policy (kaunsa traffic kis padosi se jayega — paisa, contracts, trust). Protocol: sirf BGP.

16.2 RIP (Routing Information Protocol)

  • Distance vector, metric = hop count (har link cost 1), max 15 hops (16 = infinity).
  • Har 30 sec mein padosiyon ko poori routing table bhejta hai (RIP advertisement, max 25 destination entries).
  • 180 sec tak koi advertisement na aaye → neighbour dead maano, routes invalidate karo, padosiyon ko batao.
  • UDP port 520 pe chalta hai, application-level process (routed daemon) ke roop mein.
  • Weaknesses: chhote networks tak hi (15 hops), hop count bandwidth ignore karta hai (1 Gbps aur 1 Mbps dono cost 1!), slow convergence, count-to-infinity.

16.3 OSPF (Open Shortest Path First) ★★ common

  • Link state + Dijkstra. "Open" = publicly available spec.
  • Har router poore AS mein flooding se link state advertisements (LSA) bhejta hai — seedha IP ke upar (protocol 89), TCP/UDP nahi.
  • Advanced features: authentication (fake LSA se bachav), multiple same-cost paths (ECMP load balancing), ToS-based routing (alag traffic ke liye alag cost), integrated uni/multicast.
  • Hierarchical OSPF — bade AS ke liye do level: local areas + backbone (area 0). Area ke andar detail flood hoti hai, bahar sirf summary. Area border routers areas ko jodte hain; boundary routers doosre AS se.
  • Messages: HELLO (neighbour discovery/keepalive), Database Description, Link State Request/Update/Ack.
RIP vs OSPF ek line mein

RIP = distance vector, hop count, 15 hop limit, UDP 520, simple par slow aur limited. OSPF = link state, cost-based (bandwidth), hierarchical areas, authentication, ECMP, IP protocol 89 — bade enterprise networks ka standard.

16.4 BGP — Border Gateway Protocol ★★★ asked a lot

BGP kya hai

Internet ka de facto inter-domain routing protocol — "the glue that holds the Internet together". Ye ek path vector protocol hai (distance vector ka variant jisme poora AS-path bhi jaata hai). TCP port 179 pe chalta hai.

Do flavours:

  • eBGP — doosre AS ke gateway router se prefix reachability info lena/dena.
  • iBGP — apne AS ke andar baaki routers tak wo info propagate karna.

BGP kya karta hai (3 kaam): (1) padosi AS se prefix reachability seekhna, (2) apne AS ke andar propagate karna, (3) policy ke hisaab se best route chunna.

Path attributes

AttributeKaam
AS-PATHPrefix jin AS se hoke aaya unki list. Loop detection: agar apna ASN dikh jaye to route reject. Chhota AS-PATH generally better.
NEXT-HOPUs router ka IP jisse ye route aaya (AS-PATH ke pehle AS tak pahunchne ke liye)
LOCAL PREFAS ke andar ka policy value — kaunsa exit point pasand hai. Sabse pehle check hota hai. Zyada = better.
MED (Multi-Exit Discriminator)Jab do AS multiple jagah jude hain — padosi AS ko hint ki kaunse link se traffic bhejo. Kam = better.

BGP route selection order ★★ common

  1. Highest LOCAL PREF (policy decision — sabse important)
  2. Shortest AS-PATH
  3. Closest NEXT-HOP router — yehi hot potato routing hai
  4. Additional criteria (lowest MED, eBGP over iBGP, lowest router ID…)
Hot potato routing

"Garam aloo jitni jaldi ho sake haath se phenk do" — apne AS ke andar sabse kam cost wale exit point se traffic bahar nikal do, chahe end-to-end path lamba ho jaye. Kyunki apne network ke resources bachana priority hai.

BGP policy ka classic example — ye poochha jaata hai

Maano X ek customer hai jo do providers A aur B se juda hai. X ko A se seekha hua route B ko advertise nahi karna chahiye — kyunki tab A aur B ka traffic X ke through jaane lagega aur X ko transit ka paisa nahi milega (X transit AS ban jayega).

Standard export policy: customer se seekhe routes sabko batao (paisa milta hai). Provider ya peer se seekhe routes sirf customers ko batao.

BGP messages: OPEN (session start), UPDATE (naya route ya withdrawal), KEEPALIVE, NOTIFICATION (error/close).

BGP ki weakness: trust-based hai — koi galat prefix advertise kar de to traffic hijack ho sakta hai (BGP hijacking, jaise "Pakistan Telecom ne YouTube hijack kiya tha" wala famous incident). Fix attempts: RPKI, BGPsec.

16.5 SDN — Software Defined Networking

Traditional (per-router control plane)

Har router mein apna routing algorithm chalta hai; control aur data plane ek hi box mein, vendor-specific. Nayi policy lagana mushkil.

SDN

Control plane routers se alag karke ek logically centralized controller mein daal diya. Controller poore network ka view rakhta hai aur routers mein flow tables install karta hai (OpenFlow protocol se). Routers bas "dumb" fast forwarders ban jaate hain.

Faayde: centralized programmability, easier traffic engineering, vendor-neutral, network apps (load balancer, firewall) software mein likhi ja sakti hain. Google apne data centers ke beech (B4) SDN use karta hai.

Match-plus-action: OpenFlow generalized forwarding — sirf destination IP nahi, header ke kisi bhi field (MAC, IP, TCP port, VLAN) pe match karke action (forward, drop, modify, send to controller) le sakte ho. Isse ek hi device router, switch, firewall, NAT — sab ban sakta hai.

Interview mein kya bolna hai — Sections 15–16
  • LS (Dijkstra/OSPF): global info, flooding, fast convergence, error localized. DV (BF/RIP): local info, simple, count-to-infinity.
  • Count-to-infinity ka fix: split horizon + poisoned reverse + small infinity (RIP 16).
  • Intra-AS = performance (RIP/OSPF), Inter-AS = policy (BGP).
  • BGP = path vector over TCP 179; AS-PATH se loop detection; selection: LOCAL_PREF → AS-PATH → hot potato → MED.
  • SDN: control plane centralized controller mein, OpenFlow se flow tables install.
17 · link layer

Link layer services aur error detection

CRC aur Hamming code ke numericals fix aate hain. Do baar khud solve karo.

08162431

17.1 Link layer kya karta hai

Datagram ko ek node se physically judne wale agle node tak pahunchana (ek hop). Har hop pe alag link protocol ho sakta hai (WiFi pe pehla hop, Ethernet pe doosra, fiber pe teesra).

ServiceKya karta hai
FramingDatagram ko frame mein daalna — header + trailer lagana
Link access (MAC)Shared medium pe kaun kab bolega, ye decide karna
Reliable deliveryOptional — wireless jaise high-error links pe use hota hai (WiFi ACK), fiber pe nahi (waste)
Error detectionParity, checksum, CRC — hardware (NIC) mein
Error correctionKuch links pe (FEC/Hamming) — retransmission se bachne ke liye
Flow controlAdjacent nodes ke beech pacing
Half/full duplexEk time pe ek taraf ya dono taraf

Implementation: link layer NIC (Network Interface Card) mein hoti hai — hardware + firmware. Sending side: datagram encapsulate, error bits add. Receiving side: error check, datagram nikaal ke upar do.

17.2 Error detection ka basic idea

 Sender:   [ Data D ] + [ EDC ] ────────► noisy channel ────────► Receiver
                                                     ↓
                                          D' aur EDC' se check karo:
                                          error hai ya nahi?
    
Important reality check

Error detection 100% reliable nahi hoti — kuch errors bach ke nikal sakte hain (undetected errors). Bada EDC field = better detection, par zyada overhead. Isliye layers repeat karti hain (L2 pe CRC, L4 pe checksum).

17.3 Parity checking

  • Single bit parity: d data bits ke saath 1 parity bit. Even parity mein total 1s ki sankhya even honi chahiye. Sirf odd number of bit errors pakad sakta hai — 2 bits flip ho jayein to fail.
  • Two-dimensional (2D) parity: data ko rows aur columns mein arrange karo, har row aur har column ka parity bit. Ye single-bit error ko detect AND correct kar sakta hai (row aur column dono se position pata chal jaata hai). 2-bit errors detect kar leta hai.
Q1. 2D even parity: data 1010, 1101, 0110, 1001 hai. Parity bits nikalo. Agar row 2, column 3 ka bit flip ho jaye to receiver kaise pakdega aur correct karega?practice
       c1 c2 c3 c4 | row parity
 r1     1  0  1  0 |  0   (do 1s → even → 0)
 r2     1  1  0  1 |  1   (teen 1s → odd → 1 lagao)
 r3     0  1  1  0 |  0
 r4     1  0  0  1 |  0
 ─────────────────────
 col    1  0  0  0 |  1
 par

Error aane par: maano r2c3 ka 0 → 1 ho gaya. Ab row 2 mein 1s = 4 (even) par uska parity bit 1 kehta hai odd hona chahiye → row 2 mein error. Column 3 mein 1s = 3 (odd) par parity bit 0 kehta hai even → column 3 mein error.

Intersection = r2c3 → wahi bit flip karke correct kar do. Yehi 2D parity ki khoobi hai — single-bit error correction.

17.4 Hamming code (error correction) ★★ common

Kitne parity bits chahiye 2r ≥ m + r + 1   (m = data bits, r = parity/redundant bits)
Parity bits positions 1, 2, 4, 8, … (powers of 2) pe rakhe jaate hain.
Q2. 4-bit data 1011 ke liye Hamming code banao (even parity). Phir maano bit 5 flip ho gaya — receiver kaise pakdega?exam favourite

Step 1 — r nikalo: m = 4. 2r ≥ 4 + r + 1. r=3: 8 ≥ 8 ✓ → r = 3, total 7 bits.

Step 2 — positions:

Position:  1    2    3    4    5    6    7
Bit:      P1   P2   d1   P4   d2   d3   d4
Data 1011 → d1=1, d2=0, d3=1, d4=1
Position:  P1   P2    1   P4    0    1    1

Step 3 — parity calculate karo (har Pi un positions ko cover karta hai jinke binary mein wo bit set hai):

  • P1 → positions 1,3,5,7 → bits: P1, 1, 0, 1 → 1s = 2 → even ke liye P1 = 0
  • P2 → positions 2,3,6,7 → bits: P2, 1, 1, 1 → 1s = 3 → P2 = 1
  • P4 → positions 4,5,6,7 → bits: P4, 0, 1, 1 → 1s = 2 → P4 = 0

Transmitted codeword = 0 1 1 0 0 1 1 (positions 1→7)

Step 4 — bit 5 flip: received = 0 1 1 0 1 1 1

  • C1 (1,3,5,7): 0,1,1,1 → 1s = 3 → odd → error, C1 = 1
  • C2 (2,3,6,7): 1,1,1,1 → 1s = 4 → even → C2 = 0
  • C4 (4,5,6,7): 0,1,1,1 → 1s = 3 → odd → C4 = 1

Syndrome = C4 C2 C1 = 101 = 5 → position 5 mein error → us bit ko flip karke correct kar do. ✓

Hamming distance: single-bit error correct karne ke liye minimum Hamming distance 3 chahiye; d bit errors detect karne ke liye d+1, aur d errors correct karne ke liye 2d+1.

17.5 CRC — Cyclic Redundancy Check ★★★ asked a lot

Parity se kahin zyada powerful. Ethernet, WiFi, ATM — sab CRC use karte hain (hardware mein bahut fast).

Kaise kaam karta hai
  1. Dono taraf ek generator polynomial G agreed hota hai (r+1 bits).
  2. Sender data D ke peeche r zeros lagata hai, phir G se modulo-2 division (yaani XOR-based division) karta hai.
  3. Jo remainder R aaya (r bits), wo zeros ki jagah lagakar bhej deta hai. Ab pura transmitted frame G se exactly divisible hai.
  4. Receiver bhi received frame ko G se divide karta hai. Remainder 0 → no error. Non-zero → error.
Q3. Data D = 101110, generator G = 1001. CRC nikalo aur transmitted frame batao. Phir receiver ka check dikhao.super classic

Step 1: G ke 4 bits hain → r = 3 → D ke peeche 3 zeros: 101110000

Step 2 — modulo-2 division (XOR, koi carry/borrow nahi):

          1 0 1 0 1 1        ← quotient (isse matlab nahi)
      ┌──────────────
1001  │ 1 0 1 1 1 0 0 0 0
        1 0 0 1                 ← XOR
        ───────
        0 0 1 0 1
            1 0 1 1 0
            1 0 0 1
            ───────
            0 0 1 0 0
                1 0 0 0
                1 0 0 1
                ───────
                0 0 0 1 0
                    1 0 0
                    ← 3 bits bache: 011

Remainder R = 011

Transmitted frame = 101110011 (data + CRC)

Step 3 — receiver ka check: 101110011 ko 1001 se modulo-2 divide karo → remainder 000 → no error detected ✓

Agar transmission mein koi bit flip hota, to remainder non-zero aata aur frame discard ho jaata.

CRC ki taakat (ye points bolna)

r-bit CRC ke saath: (1) saare single-bit errors, (2) saare double-bit errors (agar G properly chuna ho), (3) saare odd number of errors (agar G mein factor (x+1) ho), (4) r bits se chhote saare burst errors pakde jaate hain. Standard polynomials: CRC-32 (Ethernet), CRC-16, CRC-8.

CRC vs Checksum — poochha jaata hai

Checksum (TCP/UDP/IP) — simple addition, software mein fast, par weak (kuch error patterns miss karta hai). CRC (Ethernet) — polynomial division, hardware mein fast, bahut strong (burst errors ke liye). Isliye L2 pe CRC aur L4 pe checksum — dono ka purpose alag hai.

18 · link layer

Multiple Access protocols

ALOHA efficiency aur CSMA/CD ka minimum frame size — ye do numericals pakke hain.

08162431

18.1 Problem: ek shared channel, bahut saare nodes

Do ya zyada nodes ek saath bhejein to collision ho jaati hai — signals mix, dono frames barbaad. Chahiye ek Multiple Access Protocol jo decide kare ki kaun kab bolega — aur ye decision usi shared channel pe hi karna hai (koi alag coordination channel nahi).

Ideal MAC protocol (R bps channel ke liye)
  1. Ek node bhej raha hai → usko poora R mile
  2. M nodes bhej rahe hain → har ek ko R/M mile (average)
  3. Fully decentralized (koi master node nahi, koi clock sync nahi)
  4. Simple

18.2 Teen categories

CategoryProtocolsIdeaProblem
Channel partitioningTDMA, FDMA, CDMAChannel ko time/frequency/code slots mein baant doIdle nodes ke slots waste; low load pe inefficient
Random accessALOHA, Slotted ALOHA, CSMA, CSMA/CD, CSMA/CAJab bhejna ho bhej do; collision ho to random wait ke baad retryHigh load pe collisions se efficiency giri
Taking turnsPolling, Token passingBaari-baari mauka doPolling overhead / master failure; token loss

TDMA: har node ko har round mein fixed time slot. FDMA: har node ko alag frequency band. CDMA: sab ek saath bolte hain par alag orthogonal codes se — receiver code se apna signal nikaal leta hai (cellular mein).

Polling: master node baari-baari poochhta hai "kuch bhejna hai?" — polling delay + master single point of failure. Token passing: ek token frame ghoomta rehta hai, jiske paas token wo bhej sakta hai — token lost ho jaye to problem (Token Ring, FDDI).

18.3 Pure ALOHA vs Slotted ALOHA ★★ common

Pure (unslotted) ALOHA

Frame ready hua → turant bhej do. Koi sync nahi. Collision hui to random time baad retry.

Vulnerable time = 2 × Tframe — kyunki frame se pehle wale T time mein ya baad ke T time mein koi bhi bole to collision.

S = G·e−2G · max efficiency = 1/(2e) ≈ 0.184 = 18.4% (G = 0.5 pe)
Slotted ALOHA

Time ko slots mein baanta (1 slot = 1 frame time), sab nodes synchronized. Frame sirf slot ki shuruat mein bhej sakte ho.

Vulnerable time = 1 × Tframe — sirf usi slot mein koi aur bole to collision.

S = G·e−G · max efficiency = 1/e ≈ 0.368 = 36.8% (G = 1 pe)

S = throughput (successful frames per frame-time), G = offered load (attempted transmissions per frame-time). Slotted, pure se exactly double efficient hai — kyunki vulnerable period aadha ho gaya.

Q1. ALOHA network 200-bit frames bhejta hai 200 kbps ke shared channel pe. System 1000 frames per second banata hai. Pure aur slotted ALOHA ke liye throughput nikalo.numerical

Frame time Tfr = 200 bits / 200,000 bps = 1 ms

G = frames per frame-time = 1000 frames/sec × 0.001 sec = 1

Pure ALOHA: S = G·e−2G = 1 × e−2 = 1 × 0.135 = 0.135
→ 1000 × 0.135 = 135 frames per second successful (baaki collide)

Slotted ALOHA: S = G·e−G = 1 × e−1 = 0.368
→ 368 frames per second successful

18.4 CSMA — Carrier Sense Multiple Access

Basic idea: "bolne se pehle suno" — channel busy hai to mat bhejo. Insaan bhi yahi karte hain.

CSMA mein bhi collision hoti hai — kyun?

Propagation delay ki wajah se. Node A ne bhejna shuru kiya, par signal ko B tak pahunchne mein time lagta hai. Us beech B ne channel "free" sunke apna transmission shuru kar diya → collision. Isliye vulnerable time = propagation delay (Tp).

Persistence methods

MethodChannel busy mile toTrade-off
1-persistentSunte raho, free hote hi turant bhejo (probability 1)Zyada collision (sab ek saath toot padte hain), par kam delay. Ethernet yahi use karta hai.
Non-persistentRandom time wait karo, phir dobara sense karoKam collision, par channel idle reh sakta hai (waste)
p-persistentSlotted channel: free hone pe probability p se bhejo, (1−p) se agle slot tak rukoBeech ka raasta — dono ka balance

18.5 CSMA/CD — Collision Detection ★★★ asked a lot

Ethernet ka protocol: "listen before talk" + "listen while talking". Collision detect hote hi transmission abort kar do — kyunki aage bhejna waste hai. Isse channel waste kam hota hai.

Ethernet CSMA/CD algorithm:

  1. NIC datagram le ke frame banata hai.
  2. Channel idle hai → bhejna shuru. Busy hai → idle hone tak wait, phir bhejo (1-persistent).
  3. Poora frame bina collision ke chala gaya → done.
  4. Collision detect hui → abort karo aur 48-bit jam signal bhejo (taaki sabko pata chal jaye).
  5. Binary exponential backoff: m-th collision ke baad {0, 1, 2, …, 2m−1} mein se random K chuno aur K × 512 bit-times wait karo. 10 collisions ke baad max 1023 pe cap, 16 baar fail hone par frame drop.
Minimum frame size — sabse zyada poochha jaane wala CSMA/CD numerical Ttrans ≥ 2 × Tprop   yaani   L / R ≥ 2 × d / s

Lmin = 2 × R × d / s = R × RTT
Ye condition kyun zaroori hai (intuition)

Collision detect karne ke liye sender ko transmit karte waqt hi collision ka signal wapas milna chahiye. Sabse bura case: A ne bhejna shuru kiya, signal B tak pahunchne hi wala tha (Tp) tab B ne bhi bhej diya — B ka signal A tak aane mein aur Tp lagega. To A ko 2Tp tak transmit karte rehna hoga, warna wo frame khatam karke chala jayega aur usse pata hi nahi chalega ki collision hui thi.

Q2. 10 Mbps Ethernet, maximum cable length 2500 m (repeaters ke saath), signal speed 2×108 m/s. Minimum frame size nikalo. Kya ye 64 bytes se match karta hai?super classic

Tprop = 2500 / (2×108) = 12.5 μs

2 × Tprop = 25 μs (ye RTT hai)

Lmin = R × 2Tp = 10 × 106 × 25 × 10−6 = 250 bits

Standard Ethernet ka minimum frame 512 bits = 64 bytes rakha gaya — safety margin ke liye (repeaters ke delays, worst-case topology). Isi liye chhote frames mein padding daalni padti hai.

Follow-up: "Gigabit Ethernet mein kya hua?" → 1 Gbps pe 64-byte frame ka transmission time bahut kam ho jaata, to distance limit ~20 m ho jaati. Isliye Gigabit Ethernet ne carrier extension (frame ko 512 bytes tak extend karna) aur frame bursting introduce kiya — aur practically aaj sab full-duplex switched hai, jahan CSMA/CD ki zaroorat hi nahi.

CSMA/CD efficiency Efficiency = 1 / (1 + 5·tprop/ttrans)
tprop → 0 ya ttrans → ∞ hone pe efficiency → 1. Yaani chhoti LAN + bade frames = better.

18.6 CSMA/CA (WiFi) — collision avoidance

Wireless mein CD kyun nahi ho sakta?
  1. Half duplex radio — apni transmission itni tez hoti hai ki doosron ka weak signal sunayi hi nahi deta.
  2. Hidden terminal problem — A aur C dono AP se jude hain par ek doosre ko sun nahi sakte (deewar/distance) → dono AP pe collide karte hain aur unhe pata bhi nahi chalta.
  3. Exposed terminal problem — node channel busy sunkar ruk jaata hai, jabki uski transmission actually collide nahi karti.

CSMA/CA ka solution: collision avoid karo — sense karo, DIFS ka wait, random backoff counter (busy hone pe freeze), phir bhejo. Receiver SIFS ke baad ACK bhejta hai (kyunki sender ko khud pata nahi chalega ki frame gaya ya nahi). Optionally RTS/CTS handshake — chhote RTS/CTS frames se channel reserve karo, isse hidden terminal problem kam hoti hai.

Interview mein kya bolna hai — Sections 17–18
  • CRC modulo-2 division, remainder append; receiver ka remainder 0 → no error. Burst errors ke liye strong.
  • Hamming: 2r ≥ m+r+1, parity bits powers-of-2 positions pe, syndrome se error position.
  • Pure ALOHA 18.4%, Slotted 36.8% (vulnerable time aadha).
  • CSMA/CD: 1-persistent + collision detect + jam + binary exponential backoff; Lmin = R × 2Tprop (Ethernet 64 bytes).
  • WiFi CSMA/CA use karta hai kyunki radio half-duplex hai aur hidden terminals hote hain; ACK + RTS/CTS.
19 · link layer

Ethernet, switches, VLAN aur MPLS

Switch ka self-learning aur "switch vs router" — dono interview mein pakke hain.

08162431

19.1 Ethernet — LAN ka raja

Sabse zyada use hone wali LAN technology. Sasta, simple, aur 10 Mbps se 400 Gbps tak evolve kar gaya. Bob Metcalfe ne 1970s mein banaya.

 Ethernet frame structure

 ┌──────────┬──────┬────────┬────────┬──────┬─────────────────┬──────┐
 │ Preamble │ Dest │ Source │  Type  │ Data (payload)        │ CRC  │
 │ 8 bytes  │ MAC  │  MAC   │2 bytes │ 46 – 1500 bytes       │4 byte│
 │          │6 byte│ 6 byte │        │                       │      │
 └──────────┴──────┴────────┴────────┴──────┴─────────────────┴──────┘

 Preamble: 7 bytes of 10101010 + 1 byte 10101011 — receiver clock sync ke liye
 Type: upar wala protocol (0x0800 = IPv4, 0x0806 = ARP, 0x86DD = IPv6)
 Min frame = 64 bytes (14 header + 46 data + 4 CRC), Max = 1518 bytes
    
Ethernet ke 3 characteristics
  1. Connectionless — koi handshake nahi sending aur receiving NIC ke beech.
  2. Unreliable — receiving NIC ACK/NAK nahi bhejta. CRC fail hua to frame chupchap drop kar deta hai. Recovery TCP ka kaam hai (agar TCP use ho raha ho).
  3. MAC protocol = unslotted CSMA/CD with binary exponential backoff (shared medium pe; modern full-duplex switched Ethernet mein collision hi nahi hoti).

Ethernet standards: 10BASE-T, 100BASE-TX (Fast Ethernet), 1000BASE-T (Gigabit), 10GBASE-… — naming: speed BASE media. Sabka frame format same hai, sirf physical layer aur speed alag.

19.2 MAC address ★★ common

  • 48-bit (6 bytes), hex mein likha jaata hai: 1A-2F-BB-76-09-AD.
  • NIC ke ROM mein burned hota hai (software se badla ja sakta hai). IEEE allocate karta hai — pehle 3 bytes = manufacturer (OUI).
  • Flat address space — portable hai. LAN badal do, MAC wahi rahega. IP hierarchical hai — network badla to IP badalna padega.
  • Broadcast MAC = FF-FF-FF-FF-FF-FF (sab NICs receive karti hain).
  • First byte ka LSB: 0 = unicast, 1 = multicast.
MAC vs IP — best analogy

MAC address = tumhara Aadhaar/PAN number — permanent, kahin bhi jao wahi rahega, par usse tumhara ghar dhoondha nahi ja sakta.
IP address = tumhara postal address — jahan raho waisa milega, aur usme hierarchy hai (state → city → area → house) jisse routing possible hoti hai.

Dono kyun chahiye? LAN pe kaam karne wale saare protocols sirf IP nahi hain (ARP, older protocols), aur agar NIC mein IP hard-code karte to har network change pe hardware badalna padta. Layering ka faayda: L2 ko L3 se independent rakha.

19.3 Hub vs Bridge vs Switch vs Router ★★★ asked a lot

Hub / RepeaterBridgeSwitchRouter
LayerL1L2L2L3
KaamBits ko sab ports pe repeat2–4 LAN segments jodta hai, MAC se filterMulti-port bridge, har port dedicatedNetworks jodta hai, IP se forward
TableNahiMAC table (self-learning)MAC/CAM table (self-learning)Routing/forwarding table (protocols se)
Collision domainSab ekPer portPer portPer port
Broadcast domainEkEkEk (VLAN se todo)Per port — broadcast rokta hai
Simultaneous transmissionsNahiHaanHaanHaan
ConfigurationPlug & playPlug & playPlug & play (self-learning)IP config chahiye (manual/DHCP)

19.4 Switch self-learning ★★★ asked a lot

Teen rules — bas itna hi hai
  1. Learn: Jab frame aaye, uska source MAC aur incoming port table mein daal do (TTL ke saath, typically 60 sec).
  2. Forward: Agar destination MAC table mein hai → sirf us port pe bhejo. (Agar wahi port hai jahan se aaya → drop/filter, kyunki wo already pahunch chuka hai.)
  3. Flood: Destination MAC table mein nahi hai (ya broadcast hai) → saare ports pe bhejo, sirf incoming ko chhod ke.
Q1. Ek switch ke 4 ports hain: A (port 1), B (port 2), C (port 3), D (port 4). Table khaali hai. Ye events hote hain: (i) A → B, (ii) B → A, (iii) C → A, (iv) A → C. Har step pe table aur switch ka action batao.must know

(i) A → B:

  • Learn: A ↔ port 1 table mein add.
  • B table mein nahi hai → flood (ports 2, 3, 4 pe bhejo).
  • Table: {A:1}

(ii) B → A:

  • Learn: B ↔ port 2.
  • A table mein hai (port 1) → sirf port 1 pe bhejo (selective forward). C aur D ko frame nahi dikhega.
  • Table: {A:1, B:2}

(iii) C → A:

  • Learn: C ↔ port 3.
  • A table mein hai → sirf port 1.
  • Table: {A:1, B:2, C:3}

(iv) A → C:

  • A already table mein (refresh timer).
  • C table mein hai (port 3) → sirf port 3.
  • Table: {A:1, B:2, C:3} — D abhi tak unknown, kyunki usne kuch bheja hi nahi.

Key insight: switch sirf source addresses se seekhta hai, destination se nahi. Isliye jo device kabhi kuch bhejta hi nahi, wo table mein aata hi nahi.

Switch loop aur STP

Agar do switches ke beech redundant links ho to broadcast frame ghoomta rahega — broadcast storm (koi TTL nahi hota L2 mein!). Isliye Spanning Tree Protocol (STP, 802.1D) chalta hai jo redundant links ko block karke loop-free tree banata hai, aur link fail hone par blocked link ko activate kar deta hai.

19.5 Switch vs Router — ek line ka jawab

Switch: L2, MAC address, plug-and-play (self-learning), fast (hardware), par bade network mein broadcast storm ka problem aur flat addressing scale nahi karti.

Router: L3, IP address, hierarchical addressing se scale karta hai, broadcast domain todta hai, best-path routing karta hai, par per-packet processing zyada aur configuration chahiye.

Practical: LAN ke andar switch, networks jodne ke liye router. Ghar ka "WiFi router" actually router + switch + access point + NAT + DHCP server — sab ek box mein.

19.6 VLAN — Virtual LAN ★★ common

Problem: ek badi switched LAN mein (a) sab ek hi broadcast domain hain — ek ARP broadcast poore network mein jaata hai, (b) security/isolation nahi (HR aur Engineering ek hi LAN pe), (c) koi banda floor badle to physically cable badalni padti.

Solution: ek hi physical switch ko multiple logical LANs mein baant do. Har VLAN apna alag broadcast domain hai.

  • Port-based VLAN: switch ke ports ko VLAN ID assign karte hain (ports 1–8 = VLAN 10 "EE", ports 9–16 = VLAN 20 "CS").
  • Inter-VLAN routing: VLAN 10 se VLAN 20 baat karne ke liye router (ya L3 switch) chahiye — kyunki alag broadcast domain matlab alag subnet. ("Router on a stick" configuration.)
  • Trunk port + 802.1Q: ek hi physical link se multiple VLANs ka traffic bhejne ke liye frame mein 4-byte VLAN tag lagta hai (VLAN ID 12 bits → 4096 VLANs). Isse Ethernet frame ka max size 1518 → 1522 bytes ho jaata hai.

19.7 MPLS aur virtual circuits (bonus)

Virtual Circuit (VC): datagram network ka ulta — connection setup hota hai, har packet mein VC number hota hai (poora destination address nahi), aur har router mein per-VC state hoti hai. Har hop pe VC number badal sakta hai (label swapping). ATM, Frame Relay, X.25 ne use kiya.

MPLS (Multiprotocol Label Switching): IP aur link layer ke beech ek "2.5 layer". Packet ke aage 32-bit MPLS header lagta hai jisme 20-bit label hota hai. Router (LSR) sirf label dekhta hai — poora IP longest-prefix-match nahi karta → fast forwarding.

  • Faayda: traffic engineering — tum path choose kar sakte ho (IP mein sirf shortest path milta hai). QoS, VPNs, aur fast reroute.
  • MPLS routers IP-only routers ke saath interoperate kar sakte hain (backward compatible).
  • Signaling: OSPF/IS-IS ko extend karke labels distribute kiye jaate hain (RSVP-TE, LDP).
20 · link layer

ARP — IP se MAC tak

Chhota topic, par interview mein har baar aata hai. Walk-through zaroor yaad karo.

08162431

20.1 ARP kya karta hai ★★★ asked a lot

Definition

Address Resolution Protocol — same LAN pe kisi IP address ka MAC address pata karna. Frame bhejne ke liye destination MAC chahiye, par application ko sirf IP pata hai — ye gap ARP bharta hai.

ARP table har host/router ke paas hoti hai: <IP address, MAC address, TTL>. TTL typically 20 minutes.

  1. A ko B ka MAC nahi pata → A ek ARP query broadcast karta hai (dest MAC = FF-FF-FF-FF-FF-FF): "Kiske paas IP 192.168.1.5 hai?"
  2. LAN ke saare nodes wo frame receive karte hain.
  3. Jiska IP match karta hai (B), wo unicast mein ARP reply bhejta hai apne MAC ke saath.
  4. A apni ARP table mein entry cache kar leta hai (TTL tak).
Do line ka answer

"ARP is plug-and-play — tables automatically ban jaati hain, koi admin configure nahi karta. Aur ye sirf apne subnet ke liye hai — doosre subnet ke IP ke liye ARP nahi hoti, uske liye default gateway ka MAC resolve hota hai."

ARP kis layer ka protocol hai?

Debate hai — ARP L2 aur L3 ke beech kaam karta hai. Sabse safe answer: "ARP ek link-layer protocol hai jo network-layer addresses ko resolve karta hai; ARP messages Ethernet frame mein directly encapsulate hote hain (EtherType 0x0806), IP datagram ke andar nahi."

20.2 Doosre subnet mein bhejna — poora walkthrough ★★★ asked a lot

Ye sequence samajh gaye to CN ka aadha syllabus samajh gaye. A (subnet 1) se B (subnet 2) ko datagram bhejna hai, beech mein router R hai.

   Subnet 1                    R                     Subnet 2
  ┌────────┐          ┌──────────────────┐          ┌────────┐
  │   A    │──────────│ R1        R2     │──────────│   B    │
  │IP: A   │          │IP: R1   IP: R2   │          │IP: B   │
  │MAC: A  │          │MAC: R1  MAC: R2  │          │MAC: B  │
  └────────┘          └──────────────────┘          └────────┘
    
  1. A apna IP datagram banata hai: source IP = A, destination IP = B. (Ye poore safar mein nahi badlega.)
  2. A dekhta hai (apne subnet mask se) ki B doosre subnet mein hai → to frame default gateway (R1) ko bhejna hoga.
  3. A ko R1 ka MAC chahiye → ARP (agar cache mein nahi hai). R1 apna MAC bhej deta hai.
  4. A frame banata hai: src MAC = A, dest MAC = R1, payload mein IP datagram (A → B).
  5. R frame receive karta hai, IP datagram nikalta hai, routing table dekh ke pata karta hai ki B interface R2 se jayega. TTL−1, checksum recompute.
  6. R ko B ka MAC chahiye → ARP subnet 2 pe. B apna MAC deta hai.
  7. R naya frame banata hai: src MAC = R2, dest MAC = B, wahi IP datagram andar.
  8. B frame receive karta hai, datagram nikaal ke upar transport layer ko de deta hai.
Sabse important takeaway — ye interview ka trick question hai

Source aur destination IP addresses poore raaste mein same rehte hain (NAT na ho to). Lekin source aur destination MAC addresses har hop pe badalte hain, kyunki MAC sirf ek link ke liye meaningful hai.

Analogy: courier ka final address (IP) parcel pe likha rehta hai; par har city mein alag delivery boy (MAC) use uthata hai.

20.3 ARP spoofing (security)

ARP mein koi authentication nahi hai — jo bhi reply bhej de, host maan leta hai. Attacker fake ARP reply bhej ke keh sakta hai "gateway ka MAC main hoon" → poora traffic uske through jayega (Man-in-the-Middle). Isse ARP cache poisoning kehte hain.

Bachav: static ARP entries (critical hosts ke liye), Dynamic ARP Inspection (DAI) switches pe, port security, aur upar TLS use karna (taaki MITM data padh na sake).

Q1. Ping karte waqt exactly kaunse protocols involve hote hain, order mein?★★ common

ping 8.8.8.8 karne pe:

  1. Host dekhta hai 8.8.8.8 doosre subnet mein hai → default gateway chahiye.
  2. ARP — gateway ka MAC pata karo (agar cache mein nahi).
  3. ICMP Echo Request banega → IP datagram mein wrap → Ethernet frame mein (dest MAC = gateway).
  4. Router se router hop karte hue destination tak (har hop pe naya L2 frame, TTL−1).
  5. Destination ICMP Echo Reply bhejta hai.
  6. Host RTT calculate karta hai.

Agar ping google.com karo to sabse pehle ek DNS query (UDP 53) bhi hogi.

Interview mein kya bolna hai — Sections 19–20
  • Ethernet frame: 6+6 MAC, type, 46–1500 payload, 4-byte CRC; connectionless aur unreliable.
  • Switch = self-learning (source MAC se), forward/flood/filter, per-port collision domain, plug-and-play.
  • MAC flat & permanent (NIC), IP hierarchical & location-based (routing ke liye).
  • ARP = IP→MAC on same subnet, broadcast query + unicast reply, cached with TTL.
  • IP addresses end-to-end same; MAC addresses har hop pe badalte hain.
  • VLAN = ek switch pe kai broadcast domains; inter-VLAN traffic ke liye router chahiye; trunk pe 802.1Q tag.
21 · extras

Wireless basics aur network security

Slides mein kam hai par interviews mein aata hai — isliye compact version.

08162431

21.1 WiFi (802.11) — jitna chahiye

  • Infrastructure mode: devices ek Access Point (AP) se jude, AP wired network se juda. Ad-hoc mode: devices seedha aapas mein.
  • Association: host beacon frames sunta hai (SSID + AP MAC), ek AP chunta hai, association request bhejta hai, phir typically DHCP se IP leta hai.
  • Passive scanning = AP ke beacons ka wait; Active scanning = probe request broadcast karna.
  • Bands: 2.4 GHz (zyada range, kam speed, crowded — 11 channels jinme sirf 1, 6, 11 non-overlapping) aur 5 GHz (zyada speed, kam range). 6 GHz WiFi 6E mein.
  • MAC: CSMA/CA (Section 18 dekho) + link-layer ACK, kyunki wireless mein error rate zyada hai.
  • Security evolution: WEP (toota hua) → WPA → WPA2 (AES-CCMP) → WPA3 (SAE handshake).
Wireless links wired se alag kyun hain

(1) Signal strength distance ke saath girti hai (path loss), (2) interference doosre devices se (microwave, Bluetooth), (3) multipath propagation — signal alag-alag raaston se alag time pe pahunchta hai, (4) SNR ke hisaab se error rate badalta hai — isliye adaptive modulation (rate adaptation) hoti hai.

21.2 Security ke 4 goals ★★ common

GoalMatlabMechanism
ConfidentialitySirf intended receiver padh sakeEncryption (AES, RSA)
IntegrityMessage beech mein badla na hoHash + MAC (HMAC), digital signature
AuthenticationDoosra banda wahi hai jo bolta haiCertificates, nonce challenge, passwords
Availability / Access controlService chalti rahe, sirf authorized log use kareinFirewalls, rate limiting, DDoS protection

Symmetric vs Asymmetric encryption

Symmetric (AES, DES)Asymmetric / Public key (RSA, ECC)
KeysEk hi shared secret keyPublic key (sabke liye) + private key (sirf owner)
SpeedBahut fastSlow (100–1000× slower)
ProblemKey exchange kaise karein?Slow, bade data ke liye impractical
UseActual data encryptionKey exchange + digital signatures

Isiliye TLS hybrid hai: asymmetric se authenticate karke ek symmetric session key establish karo, phir saara data symmetric se. (Section 4.9 dekho.)

Digital signature: sender message ka hash apni private key se encrypt karta hai. Koi bhi uski public key se decrypt karke hash verify kar sakta hai → isse authentication + integrity + non-repudiation milta hai.

Certificate (X.509): ek CA (Certificate Authority) gawah banti hai ki "ye public key sach mein google.com ki hai", aur us binding pe apna digital signature laga deti hai. Browser mein root CAs pehle se installed hote hain — wahi trust chain ka anchor hai.

21.3 Common attacks (rapid list)

AttackKya hota haiBachav
Packet sniffingShared medium pe promiscuous mode se sab padhnaEncryption (TLS/WPA2)
IP spoofingFake source IP se packet bhejnaIngress filtering, authentication
MITMBeech mein baith ke padhna/badalnaTLS + certificate verification
DoS / DDoSBandwidth/connection resources bhar dena (botnet se)Rate limiting, filtering, scrubbing services, anycast
SYN floodHalf-open connections se server ki table bharnaSYN cookies
ARP spoofingFake ARP reply se traffic apni taraf mod lenaDynamic ARP Inspection, static entries
DNS cache poisoningResolver ko fake mapping cache karwa denaDNSSEC, random query IDs + source ports
BGP hijackingGalat prefix advertise karke traffic kheenchnaRPKI, route filtering

Firewall types: (1) Stateless packet filter — har packet ko header rules se allow/deny. (2) Stateful filter — connection state track karta hai (sirf established connections ke reply allow). (3) Application gateway/proxy — application data tak dekhta hai (jaise sirf kuch users ko Telnet allow).

VPN: public Internet ke upar ek encrypted tunnel (IPsec/WireGuard/OpenVPN) — remote employees ko aisa lagta hai jaise wo office LAN pe hon.

22 · the big one

"google.com type karne pe kya hota hai?" — poora jawab

Ye sabse zyada poochha jaane wala CN interview question hai. Ye ek section pura yaad kar lo — isme har layer aa jaati hai.

08162431
Interview strategy

Pehle high-level 6-7 steps bolo (30 seconds). Phir interviewer jis step pe "aur detail batao" bole, wahan deep jao. Sab kuch ek saath mat bol dena — wo confusing lagta hai.

22.1 Chhota version (jo pehle bolna hai)

  1. Browser URL parse karta hai; cache check karta hai.
  2. DNS se google.com ka IP nikalta hai.
  3. Us IP ke saath TCP 3-way handshake (port 443).
  4. TLS handshake — certificate verify, session key.
  5. HTTP GET request jaati hai, server response deta hai.
  6. Browser HTML parse karta hai, aur objects (CSS/JS/images) ke liye aur requests bhejta hai.
  7. Render — DOM + CSSOM → render tree → layout → paint.

22.2 Poora version (jab detail maangein)

Phase 0 — Network se judna (agar naya connect hua ho)

  • DHCP DORA — laptop ko IP, subnet mask, default gateway, DNS server milta hai. Ye messages UDP (68→67) mein, IP broadcast (255.255.255.255) mein, aur Ethernet broadcast (FF:FF:FF:FF:FF:FF) frame mein jaate hain.
  • ARP — default gateway ka MAC pata karna, kyunki har outgoing frame usi ko jayega.

Phase 1 — URL resolution (DNS)

  • Browser check karta hai: browser cache → OS cache (/etc/hosts bhi) → router cache → ISP resolver cache.
  • Miss hone par local DNS resolver iterative queries karta hai: root → .com TLD → google.com ka authoritative server.
  • Query UDP port 53 pe jaati hai. Answer TTL ke saath cache ho jaata hai.
  • Aksar CDN involved hota hai — tumhari location ke hisaab se nearest edge server ka IP milta hai.

Phase 2 — Transport connection

  • OS ek ephemeral source port choose karta hai; socket = (src IP, src port, dst IP, 443).
  • 3-way handshake: SYN → SYN-ACK → ACK. Yahin MSS, window scaling, SACK jaise options negotiate hote hain.
  • Beech mein packet har hop pe: L3 routing (longest prefix match, TTL−1), L2 pe naya frame har link ke liye.

Phase 3 — TLS

  • ClientHello (cipher suites, SNI) → ServerHello + certificate → certificate chain verify (CA signature, validity, hostname match, revocation) → key exchange (ECDHE) → session keys → Finished.
  • TLS 1.3 mein ye 1 RTT mein ho jaata hai (aur resumption pe 0-RTT).

Phase 4 — HTTP

  • GET / HTTP/1.1 + Host header + cookies + Accept-Encoding (gzip/br).
  • Server response: status line + headers (Content-Type, Content-Length/Transfer-Encoding, Cache-Control, Set-Cookie) + body.
  • Redirect (301/302) hua to browser naye URL pe dubara sab kuch karta hai (aksar http → https redirect, ya HSTS se seedha https).

Phase 5 — Rendering

  • HTML parse → DOM; CSS → CSSOM; JS execute (parser block kar sakta hai).
  • Har referenced object ke liye phir se HTTP request (HTTP/2 mein same connection pe multiplexed streams).
  • Layout → paint → composite.

Phase 6 — Connection close

  • Keep-alive timeout ya explicit close → 4-way FIN handshake, phir TIME_WAIT (2×MSL).
Har layer kahan use hui — ye summary bolna impress karta hai
LayerKya hua
ApplicationDNS, HTTP, TLS
TransportUDP (DNS), TCP (handshake, reliability, flow/congestion control), ports
NetworkIP addressing, routing (LPM), TTL, NAT, ICMP (errors), fragmentation
LinkARP, Ethernet/WiFi framing, MAC addresses, CSMA/CA, switch forwarding
PhysicalBits over WiFi radio / copper / fiber
Follow-up: "Page slow load ho raha hai — tum kaise debug karoge?" (system-design flavour)★★ common

Layer by layer chalo — ye structured approach interviewer ko pasand aata hai:

  1. Physical/Link: WiFi signal, packet loss — ping se loss % dekho.
  2. Network: traceroute — kis hop pe latency spike ho raha hai? Koi routing loop?
  3. DNS: dig/nslookup se resolution time — DNS slow to pehla byte hi late aayega.
  4. Transport: RTT zyada? Packet loss se congestion window chhoti reh rahi hai? Wireshark se retransmissions dekho.
  5. Application: browser DevTools Network tab — TTFB (time to first byte) zyada hai to server-side problem; content download time zyada hai to bandwidth/asset size problem; bahut saare requests hain to HTTP/2, bundling, ya CDN chahiye.
  6. Fixes: CDN, caching headers, compression (gzip/brotli), fewer round trips, connection reuse, HTTP/3.
23 · revision

Rapid-fire interview Q&A (50)

Har question ka answer 20–40 seconds mein bolna hai. Pehle khud bolo, phir kholo.

08162431

Basics & layering

1. OSI aur TCP/IP model mein difference?

OSI 7 layers, theoretical reference model (ISO), protocol se pehle bana. TCP/IP 4–5 layers, practical, protocols pehle bane phir model. OSI mein presentation aur session alag layers hain, TCP/IP mein wo application ke andar. Internet TCP/IP pe chalta hai.

2. Har layer ka PDU kya hota hai?

Application/Presentation/Session: data/message. Transport: segment (TCP) / datagram (UDP). Network: packet/datagram. Data link: frame. Physical: bits.

3. Encapsulation kya hai?

Data jab neeche wali layers se guzarta hai, har layer apna header (aur link layer trailer bhi) add karti hai. Receiver pe ulta process — decapsulation.

4. Latency, bandwidth, throughput mein difference?

Bandwidth = maximum theoretical capacity (bps). Throughput = actually achieve hua rate. Latency = ek packet ko pahunchne mein laga time (ms). Analogy: pipe ki motai = bandwidth, actual paani = throughput, ek boond ko pahunchne ka time = latency.

5. Transmission delay aur propagation delay?

Transmission = L/R (packet ke bits ko link pe push karna — packet size aur bandwidth pe depend). Propagation = d/s (ek bit ka safar — distance aur medium pe depend). Ek dusre se independent hain.

6. Circuit switching vs packet switching?

Circuit: pehle dedicated path reserve, guaranteed rate, idle mein waste (telephone). Packet: on-demand sharing, statistical multiplexing, zyada users, par queuing delay aur loss ho sakta hai (Internet).

7. Router, switch, hub, bridge, gateway — sabka farak?

Hub L1 (sab ports pe repeat), bridge/switch L2 (MAC se forward, self-learning), router L3 (IP se forward, broadcast domain todta hai), gateway = alag protocols/networks jodne wala device (aksar router hi, par protocol translation bhi kar sakta hai).

8. Collision domain aur broadcast domain?

Collision domain = wo region jahan do transmissions takra sakti hain (hub = 1 bada; switch = per port). Broadcast domain = jahan tak broadcast frame jaata hai (switch = 1, VLAN se todo; router = per interface).

9. Unicast, broadcast, multicast, anycast?

Unicast = one-to-one. Broadcast = one-to-all (subnet ke andar). Multicast = one-to-many (interested group ko). Anycast = one-to-nearest (same IP kai jagah advertise, nearest jeetta — DNS root servers aur CDN yahi use karte hain).

10. Full duplex vs half duplex?

Half duplex = ek time pe ek hi direction (walkie-talkie; hub-based Ethernet). Full duplex = dono directions simultaneously (phone call; modern switched Ethernet — isliye ab collision hi nahi hoti).

Application layer

11. HTTP stateless kyun kehte hain aur state kaise maintain hoti hai?

Server har request ko independent treat karta hai, pichhli request ka context nahi rakhta. State cookies (session ID), server-side sessions, JWT tokens, ya URL rewriting se maintain hoti hai.

12. HTTP/1.1, HTTP/2, HTTP/3 mein difference?

1.1: text, persistent connections, app-level HOL blocking. 2: binary framing, multiplexed streams, HPACK header compression, server push — par TCP-level HOL abhi bhi. 3: QUIC over UDP — per-stream reliability (no HOL), TLS 1.3 built-in, 0/1-RTT setup, connection migration.

13. GET aur POST mein difference?

GET data URL mein, cacheable/bookmarkable, idempotent aur safe, length limited. POST data body mein, cache nahi hota, non-idempotent, size limit practically nahi. Security dono mein HTTPS se hi aati hai.

14. HTTP status code 301 vs 302, aur 401 vs 403?

301 = permanent redirect (browser/SEO update kar lete hain), 302/307 = temporary. 401 = authentication chahiye (login karo), 403 = authenticated ho par permission nahi hai.

15. Cookie aur session mein difference?

Cookie client side stored hoti hai (browser), size limited (~4KB), har request mein automatically jaati hai. Session server side hota hai; uska identifier cookie mein bhejte hain. Session zyada secure hai kyunki data client ke paas nahi hota.

16. DNS kaam kaise karta hai?

Hierarchical distributed database: root → TLD → authoritative. Client local resolver ko recursive query bhejta hai; resolver iteratively hierarchy se poochta hai aur answer cache karta hai (TTL tak). UDP port 53.

17. A record aur CNAME mein difference?

A record hostname ko seedha IPv4 address pe map karta hai. CNAME hostname ko doosre hostname (canonical name) pe map karta hai — phir uske liye dobara resolve karna padta hai. CNAME zone apex (naked domain) pe allowed nahi hota.

18. HTTP aur HTTPS mein exactly kya farak hai?

HTTPS = HTTP over TLS, port 443. TLS confidentiality (encryption), integrity (MAC), aur server authentication (certificate) deta hai. Handshake mein asymmetric crypto se symmetric session key establish hoti hai, phir data symmetric se encrypt hota hai.

19. Forward proxy aur reverse proxy?

Forward proxy client ki taraf hota hai (client ko chhupata hai, caching/filtering). Reverse proxy server ki taraf (server ko chhupata hai, load balancing, TLS termination, caching — jaise Nginx, Cloudflare).

20. CDN kaise kaam karta hai?

Content ki copies duniya bhar ke edge servers pe rakhi jaati hain. DNS (ya anycast) user ko nearest edge pe bhej deta hai. Isse latency kam, origin pe load kam, aur DDoS absorb karne ki capacity milti hai.

Transport layer

21. TCP aur UDP mein difference? Kab kaun use karein?

TCP connection-oriented, reliable, ordered, flow + congestion control, 20-byte header — web, email, file transfer ke liye. UDP connectionless, unreliable, fast, 8-byte header, broadcast/multicast support — DNS, VoIP, gaming, streaming, QUIC ke liye. Rule: data integrity chahiye to TCP; latency zyada important hai to UDP.

22. 3-way handshake kyun, 2-way kyun nahi?

Dono directions ke initial sequence numbers exchange aur acknowledge hone chahiye (connection full duplex hai). Aur purane duplicate SYN se half-open connections ban jaati — teesra ACK confirm karta hai ki client abhi bhi zinda hai aur connection chahta hai.

23. TIME_WAIT state kyun hoti hai?

(1) Agar aakhri ACK kho jaye to peer FIN retransmit karega — usko reply dene ke liye socket zinda rakhna padta hai. (2) Network mein ghoom rahe purane duplicate segments expire ho jaayein taaki wo agli same-4-tuple connection mein na ghus jaayein. Duration = 2×MSL.

24. Flow control aur congestion control?

Flow control receiver ko bachata hai (rwnd, explicit signal header mein). Congestion control network ko bachata hai (cwnd, implicit signal — loss/timeout/duplicate ACKs). Sender limit = min(cwnd, rwnd).

25. TCP slow start kya hai?

Connection cwnd = 1 MSS se shuru hota hai aur har ACK pe 1 MSS badhta hai — yaani har RTT mein cwnd double (exponential). ssthresh tak pahunchne pe congestion avoidance (linear) shuru ho jaata hai.

26. TCP Tahoe aur Reno?

Timeout pe dono cwnd = 1 kar dete hain. Farak 3 duplicate ACKs pe: Tahoe bhi cwnd = 1 karke slow start mein jaata hai; Reno cwnd = ssthresh karke fast recovery se seedha congestion avoidance mein jaata hai — isliye Reno ka throughput behtar.

27. Fast retransmit kya hai?

3 duplicate ACKs milne pe sender timeout ka intezaar kiye bina missing segment retransmit kar deta hai. Duplicate ACKs ka matlab hai ki baad ke segments pahunch rahe hain, sirf ek gap hai.

28. TCP GBN hai ya Selective Repeat?

Hybrid. Cumulative ACK aur single timer GBN jaisa; par timeout pe sirf ek segment retransmit karta hai aur receiver out-of-order segments buffer karta hai — ye SR jaisa. SACK option ke saath aur bhi SR jaisa ho jaata hai.

29. Port number kya hai, ranges?

16-bit number jo host ke andar process identify karta hai. 0–1023 well-known (system), 1024–49151 registered, 49152–65535 ephemeral/dynamic (client side).

30. Socket kya hai?

Application aur transport layer ke beech ka interface/endpoint. TCP socket 4-tuple se identify hota hai (src IP, src port, dst IP, dst port); UDP socket 2-tuple se (dst IP, dst port).

31. Head-of-line blocking kya hai?

Queue ka pehla element atak jaye to peeche wale bhi ruk jaate hain. Teen jagah aata hai: HTTP/1.1 (request queue), TCP (in-order delivery — HTTP/2 ka problem), aur router input ports (switching fabric).

32. MSS aur MTU?

MTU = link layer frame ka max payload (Ethernet 1500 bytes). MSS = TCP segment ka max application data = MTU − IP header − TCP header = 1500 − 40 = 1460 bytes typically.

33. Nagle's algorithm?

Chhote-chhote packets ki wajah se overhead na ho, isliye TCP chhote data ko jama karke bhejta hai jab tak pichhla unACKed data hai. Interactive apps (SSH, games) mein isse lag hota hai — TCP_NODELAY se band karte hain.

Network layer

34. IPv4 aur IPv6 mein difference?

32-bit vs 128-bit address; variable 20–60 byte vs fixed 40 byte header; IPv6 mein checksum nahi, router fragmentation nahi, broadcast nahi (multicast/anycast), IPsec designed-in, aur SLAAC auto-configuration.

35. Subnet mask kya batata hai?

IP address ke kaunse bits network part hain aur kaunse host part. IP AND mask = network address. /24 = 255.255.255.0 = 256 addresses = 254 usable hosts.

36. Private aur public IP?

Private ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) Internet pe route nahi hote — LAN ke andar use hote hain aur NAT se public IP mein translate hote hain. Public IPs globally unique aur routable hain.

37. NAT kaise kaam karta hai aur uske nuksaan?

Router outgoing packet ka (private IP, port) ko (public IP, naya port) se replace karta hai aur mapping table rakhta hai; reply pe ulta translate karta hai. Nuksaan: end-to-end connectivity todta hai (P2P/gaming mushkil), layering violate karta hai, aur incoming connections ke liye port forwarding/STUN/TURN chahiye.

38. DHCP ka process?

DORA: Discover (client broadcast) → Offer (server) → Request (client) → ACK (server). UDP 67/68. Client ko IP, subnet mask, default gateway, aur DNS server ka address milta hai, lease time ke saath.

39. TTL ka kaam?

Har router pe 1 kam hota hai; 0 hone pe packet drop + ICMP Time Exceeded. Isse routing loop mein packet hamesha ke liye nahi ghoomta. traceroute isi ka fayda uthata hai.

40. Fragmentation kab hoti hai aur reassembly kahan?

Jab datagram outgoing link ke MTU se bada ho. IPv4 mein router fragment kar sakta hai; reassembly hamesha destination host pe hoti hai. Identification field se group, offset (8-byte units) se position, MF flag se pata chalta hai aakhri fragment kaunsa hai.

41. Routing aur forwarding?

Routing = network-wide process jo best paths nikaal ke forwarding tables banata hai (control plane). Forwarding = ek router ke andar incoming packet ko sahi output port pe bhejna (data plane, per-packet).

42. Link state aur distance vector?

LS: har router poora topology jaanta hai (flooding se), khud Dijkstra chalata hai — fast convergence, errors localized (OSPF). DV: sirf padosiyon se distance vectors, Bellman-Ford — simple, kam memory, par count-to-infinity aur slow convergence (RIP).

43. Count-to-infinity aur uska fix?

Link fail hone par nodes ek doosre ki stale information se cost dhire-dhire badhate rehte hain. Fix: split horizon, poisoned reverse, chhota infinity (RIP mein 16), hold-down timers, triggered updates.

44. BGP kya hai aur kyun zaroori hai?

Inter-AS path vector routing protocol (TCP 179). AS ke beech reachability aur policy based routing deta hai — kyunki AS ke beech shortest path nahi, business relationships (customer/provider/peer) matter karte hain. AS-PATH se loop detection hoti hai.

Link layer

45. ARP kya karta hai?

Same subnet pe IP address se MAC address nikalta hai. Broadcast query, unicast reply, aur result ARP cache mein ~20 min TTL ke saath. Doosre subnet ke liye default gateway ka MAC resolve hota hai.

46. MAC address aur IP address mein difference?

MAC 48-bit, flat, NIC mein burned, sirf ek link ke liye meaningful, L2. IP 32/128-bit, hierarchical, network ke hisaab se assign hota hai (isliye routing possible), L3. Ek packet ke IP end-to-end same rehte hain, MAC har hop pe badalte hain.

47. Switch self-learning kaise karta hai?

Har incoming frame ka source MAC aur port table mein daal deta hai. Forwarding ke waqt destination MAC table mein mile to us port pe, na mile (ya broadcast ho) to baaki sab ports pe flood, aur agar same port pe ho to drop.

48. CSMA/CD aur CSMA/CA?

CD (wired Ethernet): transmit karte waqt collision detect karo, abort + jam + exponential backoff. CA (WiFi): collision detect ho hi nahi sakta (half-duplex radio, hidden terminals), isliye avoid karo — DIFS wait, random backoff, ACK, optional RTS/CTS.

49. Ethernet frame ka minimum size 64 bytes kyun?

CSMA/CD ke liye transmission time ≥ 2×propagation delay hona chahiye, taaki sender ko collision ka pata transmit karte-karte chal jaye. 10 Mbps aur 2500 m ke worst case ke liye ye ~512 bits = 64 bytes banta hai (safety margin ke saath).

50. VLAN kya hai aur kyun use karte hain?

Ek physical switch ko logically kai broadcast domains mein baantna. Faayde: broadcast traffic kam, department-wise isolation/security, aur physical rewiring ke bina logical grouping. Inter-VLAN communication ke liye router/L3 switch chahiye; multiple switches ke beech 802.1Q trunk tag lagta hai.

24 · practice

Numerical problem bank

Mixed problems, koi hint nahi ki kis topic ka hai — asli exam aisa hi hota hai. Pen-paper nikalo.

08162431
N1. Host A se B tak 3 links hain, har link 2 Mbps, propagation delay per link 10 ms, packet size 2 KB. Processing/queuing ignore. Ek packet ka end-to-end delay?

L = 2 KB = 2048 × 8 = 16,384 bits. L/R = 16,384 / 2×106 = 8.192 ms per link.

Store-and-forward: 3 links → 3 × 8.192 = 24.576 ms transmission.

Propagation: 3 × 10 = 30 ms.

Total = 24.576 + 30 = 54.576 ms

N2. Ek link pe 1000 packets/sec aate hain, har packet 8000 bits ka, link 10 Mbps hai. Traffic intensity nikalo. Kya ye stable hai?

La/R = (8000 bits × 1000 packets/s) / 107 bps = 8×106/107 = 0.8

0.8 < 1 → stable hai, par 1 ke kaafi paas hai. Queuing delay noticeable hoga aur bursts pe loss ho sakta hai. Design mein generally 0.7 se neeche rakhna better hai.

N3. Web page mein 1 HTML + 8 images hain, har object 100 KB. RTT = 200 ms, link 1 Mbps. Persistent HTTP (no pipelining) se total time?

Har object ka transmission time = 100 × 1024 × 8 / 106 = 819.2 kbit / 1000 kbps ≈ 0.82 s

Persistent without pipelining: 1 RTT handshake + har object ke liye (1 RTT + transmission).

= 0.2 + 9 × (0.2 + 0.82) = 0.2 + 9 × 1.02 = 0.2 + 9.18 = 9.38 s

Pipelining ke saath: 0.2 (handshake) + 0.2 (HTML request/response RTT) + 0.82 (HTML) + 0.2 (sab image requests ek saath) + 8 × 0.82 = 0.2+0.2+0.82+0.2+6.56 = 7.98 s. Yahan transmission dominate kar raha hai, isliye pipelining ka fayda utna dramatic nahi.

N4. Stop-and-wait protocol, 100 Mbps link, 20 ms one-way propagation, frame 1250 bytes. Utilization? Link ko saturate karne ke liye kitni window chahiye?

L/R = 1250 × 8 / 108 = 10,000/108 = 0.1 ms

RTT = 40 ms

U = 0.1 / (40 + 0.1) = 0.0025 = 0.25%

Window N ≥ (RTT + L/R)/(L/R) = 40.1/0.1 = 401 frames

GBN mein iske liye seq# bits: 2k − 1 ≥ 401 → 2k ≥ 402 → k = 9 bits

N5. TCP Reno. cwnd = 16 MSS, ssthresh = 16. 3 duplicate ACKs mile. Uske 4 RTT baad ek timeout ho gaya. Har event ke baad cwnd aur ssthresh batao.
Eventcwnd (baad mein)ssthreshPhase
Start1616CA
3 dup ACKs88Fast recovery → CA
+1 RTT98CA
+2 RTT108CA
+3 RTT118CA
+4 RTT → timeout16 (=12/2, kyunki timeout ke waqt cwnd 12 tha)Slow start

Dhyaan: ssthresh hamesha loss ke waqt ki cwnd ka aadha hota hai, purani ssthresh ka nahi.

N6. TCP connection ka MSS 1460 bytes hai, RTT 100 ms, aur loss rate 0.01%. Approximate throughput?

Throughput ≈ 1.22 × MSS / (RTT × √L)

= 1.22 × 1460 bytes / (0.1 s × √0.0001)

= 1781.2 / (0.1 × 0.01) = 1781.2 / 0.001 = 1,781,200 bytes/s ≈ 14.25 Mbps

Note kitna dramatic effect hai: loss rate 10× badhaoge (0.1%) to throughput √10 ≈ 3.16 times gir jayega.

N7. Block 192.168.1.0/24 ko 4 barabar subnets mein baanto. Har subnet ka network address, broadcast, aur host range likho.

4 subnets ke liye 2 bits chahiye (22 = 4) → /24 + 2 = /26, mask 255.255.255.192, block size 64.

SubnetNetworkHost rangeBroadcast
1192.168.1.0/26.1 – .62192.168.1.63
2192.168.1.64/26.65 – .126192.168.1.127
3192.168.1.128/26.129 – .190192.168.1.191
4192.168.1.192/26.193 – .254192.168.1.255

Har subnet mein 62 usable hosts.

N8. IP address 172.16.35.123 ka subnet mask 255.255.240.0 hai. Network address, broadcast address, aur is subnet mein kitne hosts?

Mask 255.255.240.0 → /20 (11111111.11111111.11110000.00000000)

Block size = 256 − 240 = 16, third octet mein → subnets: 0, 16, 32, 48, …

35 kis block mein? 32 ≤ 35 < 48 → block 32.

Network = 172.16.32.0

Broadcast = 172.16.47.255 (agla block 48 se shuru, uske ek pehle)

Hosts = 212 − 2 = 4094 (range 172.16.32.1 – 172.16.47.254)

N9. 5000-byte IP datagram (20 byte header) ko pehle 2000-byte MTU wali link se, phir 600-byte MTU wali link se guzarna hai. Final fragments kitne aur unke offsets?

Pehli link (MTU 2000): data per fragment = 2000 − 20 = 1980 → 8 ka multiple nahi (1980/8 = 247.5) → 1976 lo (1976/8 = 247 ✓).

Data total = 4980 bytes. Fragments: 1976 + 1976 + 1028 = 4980

  • F1: offset 0, len 1996, MF=1
  • F2: offset 247, len 1996, MF=1
  • F3: offset 494, len 1048, MF=0

Doosri link (MTU 600): data per fragment = 600 − 20 = 580 → 8 ka multiple nahi → 576 lo (576/8 = 72 ✓).

F1 (1976 bytes) → 576+576+576+248 = 1976 → 4 fragments, offsets 0, 72, 144, 216

F2 (1976 bytes) → 4 fragments, offsets 247, 319, 391, 463

F3 (1028 bytes) → 576+452 = 1028 → 2 fragments, offsets 494, 566

Total = 10 fragments, aur sirf aakhri wale ka MF = 0.

Key point: offsets original datagram ke relative hote hain, intermediate fragment ke nahi.

N10. Slotted ALOHA mein N = 5 nodes hain, har ek probability p = 0.2 se transmit karta hai. Ek slot mein successful transmission ki probability?

Success = exactly ek node transmit kare, baaki 4 chup rahen.

P(success) = N × p × (1−p)N−1 = 5 × 0.2 × (0.8)4

= 5 × 0.2 × 0.4096 = 0.4096 ≈ 41%

Optimal p = 1/N = 0.2 hi hai (isliye ye maximum ke paas hai). N → ∞ pe ye limit 1/e = 0.368 pe jaati hai — wahi slotted ALOHA ki max efficiency hai.

N11. 1 Gbps Ethernet, 100 m cable, signal speed 2×108 m/s. Minimum frame size CSMA/CD ke liye kitna chahiye?

Tprop = 100 / 2×108 = 0.5 μs → 2Tprop = 1 μs

Lmin = R × 2Tp = 109 × 10−6 = 1000 bits = 125 bytes

Standard Ethernet ka 64-byte minimum yahan kam pad jaata → isliye Gigabit Ethernet mein carrier extension (frames ko 512 bytes tak pad karna) aur frame bursting introduce kiya gaya. Practically aaj sab full-duplex switched hai to CSMA/CD chalta hi nahi.

N12. CRC: data = 1101011011, generator = 10011. Transmitted frame kya hoga?

G ke 5 bits → r = 4 → data ke peeche 4 zeros: 1101011011 0000

10011 ) 11010110110000
        10011
        -----
        01001110110000
          10011
          -----
          0000110110000
              10011
              -----
              00100110000... 

 Continue karte hue final remainder = 1110

Transmitted frame = 1101011011 1110

Verify: 11010110111110 ÷ 10011 → remainder 0000 ✓

Tip: modulo-2 division mein har step pe bas XOR karna hai — na carry, na borrow. Leading bit 1 ho to divisor XOR karo, 0 ho to shift.

N13. Ek router ke paas ye entries hain. Packet 200.100.50.75 ke liye kaunsa next hop?
PrefixNext hop
200.100.0.0/16A
200.100.48.0/20B
200.100.50.0/24C
0.0.0.0/0 (default)D

Check karo kaun-kaun match karte hain:

  • /16: 200.100.x.x ✓
  • /20: 200.100.48.0/20 → range 200.100.48.0 – 200.100.63.255 → 50 is in range ✓
  • /24: 200.100.50.0 – 200.100.50.255 → 75 in range ✓
  • Default ✓

Longest prefix = /24 → next hop C

N14. Client-server mein 10 GB file ko 1000 peers tak pahunchana hai. us = 100 Mbps, har peer ui = 5 Mbps, di = 50 Mbps. CS aur P2P time compare karo.

F = 10 GB = 80,000 Mbit (1 GB = 8000 Mbit)

Client-server:

  • NF/us = 1000 × 80,000 / 100 = 800,000 s
  • F/dmin = 80,000/50 = 1,600 s
  • Dcs = 800,000 s ≈ 9.3 din

P2P:

  • F/us = 800 s
  • F/dmin = 1,600 s
  • NF/(us + Σui) = 80,000,000 / (100 + 5000) = 80,000,000/5100 = 15,686 s
  • DP2P = 15,686 s ≈ 4.4 ghante

P2P ~51× faster. Aur N badhaane pe CS linearly bigadta jayega jabki P2P thoda hi.

N15. Router ke output link pe 10 Mbps capacity hai. Teen flows ke weights 1, 2, 2 hain (WFQ). Har flow ko kitni bandwidth? Agar flow 3 idle ho jaye to?

Total weight = 5.

  • Flow 1: (1/5) × 10 = 2 Mbps
  • Flow 2: (2/5) × 10 = 4 Mbps
  • Flow 3: (2/5) × 10 = 4 Mbps

Flow 3 idle: bachi hui bandwidth flow 1 aur 2 mein 1:2 ratio mein banti hai (work-conserving):

  • Flow 1: (1/3) × 10 = 3.33 Mbps
  • Flow 2: (2/3) × 10 = 6.67 Mbps
N16. Ek TCP connection ne 3-way handshake complete kiya jisme client ka ISN = 5000 aur server ka ISN = 9000 tha. Handshake ke baad client 1000 bytes bhejta hai. Har segment ke Seq aur ACK numbers likho.
#DirectionFlagsSeqACK
1C → SSYN5000—
2S → CSYN, ACK90005001
3C → SACK50019001
4C → SACK + 1000 bytes data50019001
5S → CACK90016001

Key: SYN aur FIN flags ek "phantom byte" consume karte hain — isliye ACK 5001 (5000 ka SYN + 1). Data ke 1000 bytes 5001–6000 hain, to agla expected byte 6001.

N17. Dijkstra: node A se saare nodes tak shortest paths nikalo. Edges: A-B=4, A-C=2, B-C=1, B-D=5, C-D=8, C-E=10, D-E=2, D-F=6, E-F=3.
StepSettledBCDEF
0A4,A2,A∞∞∞
1A,C3,C—10,C12,C∞
2A,C,B——8,B12,C∞
3A,C,B,D———10,D14,D
4+E————13,E

Final shortest paths from A:

  • B: A→C→B, cost 3
  • C: A→C, cost 2
  • D: A→C→B→D, cost 8
  • E: A→C→B→D→E, cost 10
  • F: A→C→B→D→E→F, cost 13

Dhyaan step 1 pe: C ke through B ka cost 2+1 = 3 mila jo direct 4 se better hai. Aur step 3 pe E ka 12 (via C) ko 10 (via D) ne replace kiya.

N18. Ek 100 Mbps link pe ek TCP flow chal rahi hai jiski RTT 50 ms hai. Link ko fully utilize karne ke liye receive window kitni honi chahiye? Kya 16-bit window field kaafi hai?

BDP = bandwidth × RTT = 100 × 106 × 0.05 = 5 × 106 bits = 625,000 bytes ≈ 610 KB

16-bit window field ka max = 65,535 bytes = 64 KB — bilkul kaafi nahi.

Solution: TCP window scaling option (RFC 7323) — SYN mein ek scale factor negotiate hota hai jisse window ko 214 tak left-shift kiya ja sakta hai (max ~1 GB). Ye "long fat network" (high BDP) problem ka standard fix hai.

25 · reference

Cheat sheet — ek page pe sab kuch

Interview se 1 ghanta pehle sirf ye section padhna. Print karke rakh lo.

08162431

25.1 Formula sheet

TopicFormula
Total delayd = dproc + dqueue + dtrans + dprop
Transmission delayL / R
Propagation delayd / s  (s ≈ 2×108 m/s)
Traffic intensityL·a / R  (→1 pe delay blow up)
Throughputmin(R1, …, Rn) — bottleneck
Store & forward, N linksN · L/R; P packets: (N + P − 1) · L/R
Stop-and-wait utilization(L/R) / (RTT + L/R)
Pipelined utilizationN·(L/R) / (RTT + L/R)
Window for full utilizationN ≥ (RTT + L/R)/(L/R); BDP = R × RTT
GBN / SR window limit2k − 1 / 2k−1
TCP timeoutEstRTT + 4·DevRTT; EstRTT = 0.875·old + 0.125·sample
TCP throughput0.75·W/RTT  or  1.22·MSS/(RTT·√L)
Sender limitLastByteSent − LastByteAcked ≤ min(cwnd, rwnd)
Subnet: hosts2(32−x) − 2; block size = 256 − mask octet
Fragment offsetbyte position / 8; payload 8 ka multiple
Pure / Slotted ALOHAS = G·e−2G (max 18.4%) / S = G·e−G (max 36.8%)
Slotted ALOHA successN·p·(1−p)N−1, optimal p = 1/N
CSMA/CD min frameLmin = R × 2·Tprop
CSMA/CD efficiency1 / (1 + 5·tprop/ttrans)
Hamming parity bits2r ≥ m + r + 1
P2P vs CS distributionDcs = max(NF/us, F/dmin); Dp2p = max(F/us, F/dmin, NF/(us+Σui))

25.2 Port numbers

PortProtocolTransportPortProtocolTransport
20/21FTP data/controlTCP110POP3TCP
22SSH / SFTPTCP143IMAPTCP
23TelnetTCP161/162SNMPUDP
25SMTPTCP179BGPTCP
53DNSUDP (TCP for large/AXFR)443HTTPS / QUICTCP / UDP
67/68DHCP server/clientUDP520RIPUDP
69TFTPUDP3306MySQLTCP
80HTTPTCP3389RDPTCP

OSPF aur ICMP transport layer use hi nahi karte — wo seedha IP ke upar hain (protocol number 89 aur 1).

25.3 Header sizes (yaad rakho)

Ethernet header 14 B + trailer 4 B IPv4 20–60 B IPv6 40 B fixed TCP 20–60 B UDP 8 B Ethernet MTU 1500 B Typical MSS 1460 B Min Ethernet frame 64 B Max Ethernet frame 1518 B (1522 with VLAN)

25.4 Protocol → layer map

LayerProtocols
ApplicationHTTP(S), DNS, SMTP, POP3, IMAP, FTP, SSH, Telnet, DHCP, SNMP, BitTorrent, QUIC
TransportTCP, UDP, SCTP
NetworkIPv4, IPv6, ICMP, IGMP, OSPF, RIP*, BGP*, IPsec
Data LinkEthernet (802.3), WiFi (802.11), ARP, PPP, STP, VLAN (802.1Q), MPLS (2.5)
PhysicalCables, hubs, repeaters, modulation schemes

* Nuance: RIP actually UDP pe chalta hai aur BGP TCP pe — to technically wo application-layer processes hain jo network layer ka kaam (routing) karte hain. Interview mein ye nuance bolna achha lagta hai. OSPF seedha IP pe (protocol 89).

25.5 Sabse common comparisons — one-liners

PairEk line ka farak
TCP vs UDPReliable + ordered + controlled vs fast + lightweight + no guarantees
Flow vs congestion controlReceiver bachao (rwnd, explicit) vs network bachao (cwnd, implicit)
Routing vs forwardingPath decide karna (global) vs packet ko port pe bhejna (local)
Switch vs routerMAC/L2/self-learning vs IP/L3/routing protocol
MAC vs IPFlat + permanent + per-link vs hierarchical + assigned + end-to-end
GBN vs SRCumulative ACK + retransmit all vs individual ACK + retransmit one
Tahoe vs Reno3 dup ACK pe cwnd = 1 vs cwnd = ssthresh (fast recovery)
LS vs DVPoora topology + Dijkstra vs padosiyon ke vectors + Bellman-Ford
Intra-AS vs Inter-ASPerformance (OSPF/RIP) vs policy (BGP)
POP3 vs IMAPDownload-and-delete vs server-side sync
Recursive vs iterative DNS"Tu laa ke de" vs "mujhe address bata, main khud jaunga"
CSMA/CD vs CSMA/CAWired: collision detect + abort vs Wireless: avoid + ACK + RTS/CTS
Circuit vs packet switchingReserved dedicated vs shared statistical multiplexing
Symmetric vs asymmetric cryptoFast + shared key vs slow + public/private key pair
26 · plan

Revision plan aur checklist

Kitna time hai uske hisaab se plan chuno.

08162431

26.1 Agar 3 din hain

DinKyaSections
Day 1Foundations + Application layer. Din ke ant mein Section 22 ek baar padhna.01, 02, 03, 04, 05, 06
Day 2Transport layer — sabse heavy din. Saare numericals khud solve karo.07, 08, 09, 10
Day 3Network + Link layer + revision.11, 12, 13, 15, 16, 17, 18, 19, 20 → phir 23, 24, 25

26.2 Agar sirf 1 din hai (emergency mode)

  1. Section 25 (cheat sheet) — 20 min, sab formulas aur comparisons.
  2. Section 23 (50 rapid-fire) — 60 min, har question loud bolke answer karo.
  3. Section 22 (google.com walkthrough) — 20 min, ye zaroor aayega.
  4. Sections 09, 10, 12, 20 — TCP, congestion control, subnetting, ARP. 2 ghante.
  5. Section 24 se 5–6 numericals solve karo. 1 ghanta.

26.3 Final checklist — tick karke jao

Bina soche bol paaoge?
  • OSI ki 7 layers + har ek ka PDU
  • TCP vs UDP (kam se kam 6 points)
  • 3-way handshake + 2-way kyun nahi
  • Flow vs congestion control
  • Slow start vs congestion avoidance
  • Tahoe vs Reno
  • DNS resolution ka poora flow
  • ARP ka kaam + "IP same, MAC badalta hai"
  • Switch self-learning ke 3 rules
  • NAT kaise kaam karta hai
  • DHCP DORA
  • google.com walkthrough (7 steps)
Bina calculator solve kar paaoge?
  • Transmission + propagation delay
  • Store-and-forward N hops
  • HTTP RTT (persistent vs non-persistent)
  • Stop-and-wait utilization + required window
  • GBN/SR window size from k bits
  • TCP timeout (EstRTT, DevRTT)
  • cwnd evolution table (Tahoe aur Reno)
  • Subnetting: network/broadcast/host range
  • VLSM allocation
  • Longest prefix match
  • IP fragmentation (offsets aur flags)
  • CRC modulo-2 division
  • Hamming code + syndrome
  • ALOHA efficiency
  • CSMA/CD minimum frame size
  • Dijkstra table

26.4 Interview mein bolne ka tareeka

  • Structure do. "Iske teen parts hain…" bolke start karo. Interviewer ko follow karna aasan hota hai.
  • Definition → why → example. Har concept isi order mein bolo.
  • Trade-off zaroor mention karo. "TCP reliable hai par overhead aur latency zyada hai" — ye maturity dikhata hai.
  • Real-world se jodo. "Isliye Netflix DASH over TCP use karta hai" jaise references bonus dete hain.
  • Nahi pata to bolo. "Mujhe exact detail yaad nahi, par mera samajhna ye hai ki…" — bakwaas banane se accha hai.
Aakhri baat

CN mein ratta lagane se kaam nahi chalta — ek packet ki journey visualise karo. Jab bhi koi concept confuse ho, khud se poochho: "abhi packet kahan hai, uske upar kaunse headers lage hain, aur agla device kya karega?" 90% sawaal isi se nikal jaate hain.

Computer Networks · zero → interview · Hinglish notes
Ctrl+P se print karo (khule hue solutions hi print honge — pehle "⊕ all" dabao).