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.
Ye page kaise padhna hai
Pehle 5 minute isko padho, warna 25 sections dekh ke ghabra jaoge.
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.
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
- Section 01–03 must hai. Basics + layering + delay formulas. Inke bina baaki sab hawa mein hai.
- 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.
- Baaki sections depth ke liye — college exam / on-campus test / SDE-1 deep rounds mein kaam aate hain.
- 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
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.
Network kya hai, Internet kaise bana hai
Hosts, links, routers, ISPs, aur switching ke do tareeke.
1.1 Sabse pehle: network ki 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:
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.
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
| Term | Matlab | Example |
|---|---|---|
| Host / End system | Network ke "kinare" pe baithi device jo application run karti hai | Laptop, phone, server, smart TV |
| Client | Request bhejne wala host | Chrome browser |
| Server | Request ka jawab dene wala, always-on host | Google ka web server |
| Link | Do devices ke beech ka physical raasta | Fiber cable, WiFi radio |
| Router | Network layer (L3) device — IP address dekh ke packet forward karta hai, networks ko jodta hai | Ghar ka "WiFi router" (actually router+switch+AP) |
| Switch | Link layer (L2) device — MAC address dekh ke frame forward karta hai, ek hi LAN ke andar | Office ka network switch |
| ISP | Internet Service Provider — tumhe Internet se jodta hai | Jio, Airtel |
| Protocol | Message format + order + action ke rules | HTTP, TCP, IP |
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 = 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)
| Type | Media | Note |
|---|---|---|
| Guided (solid raasta) | Twisted pair (UTP/STP) | Cat5e/Cat6 Ethernet, sasta, 100m limit, twisting se crosstalk kam |
| Coaxial cable | Cable TV/Internet, shared broadcast medium | |
| Fiber optic | Light se data, very high bandwidth, low error rate, immune to EMI, long distance — backbone ka raja | |
| Unguided (radio) | Terrestrial microwave / WiFi | LAN, ~10s–100s Mbps, obstacles se affected |
| Cellular (4G/5G) | Wide area, licensed spectrum | |
| Satellite | Geostationary: ~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.
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
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 switching | Packet switching | |
|---|---|---|
| Resource allocation | Reserved (dedicated) pehle se | On-demand, shared |
| Setup phase | Zaroori (call setup) | Nahi |
| Performance | Guaranteed, constant rate | Best-effort, variable |
| Idle time mein | Bandwidth waste | Koi waste nahi |
| Congestion | Nahi (par call blocked ho sakti hai) | Ho sakti hai → queuing delay, packet loss |
| Sharing technique | FDM / TDM | Statistical multiplexing |
| Example | Traditional telephone network | Internet |
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.
- Simplicity — koi call setup nahi, network core simple rehta hai.
- 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.
- 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?
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:
P(n active out of N) = C(N,n) · pn · (1−p)N−nP(>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?
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.)
- 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.
Layering: OSI model aur TCP/IP model
Sabse zyada poochha jaane wala theory question. Yahan galti nahi honi chahiye.
2.1 Layering kyun? ★★★ asked a lot
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
| # | Layer | Kaam (ek line) | PDU | Examples |
|---|---|---|---|---|
| 7 | Application | User ko network services deti hai | Message/Data | HTTP, DNS, SMTP, FTP |
| 6 | Presentation | Translation, encryption, compression (data ka "roop") | Data | SSL/TLS, JPEG, ASCII |
| 5 | Session | Session establish/manage/terminate, checkpointing | Data | NetBIOS, RPC |
| 4 | Transport | Process-to-process delivery, reliability, flow & congestion control | Segment (TCP) / Datagram (UDP) | TCP, UDP |
| 3 | Network | Host-to-host delivery across networks, routing, addressing | Packet/Datagram | IP, ICMP, OSPF, BGP |
| 2 | Data Link | Node-to-node delivery on one link, framing, MAC, error detection | Frame | Ethernet, WiFi, ARP, PPP |
| 1 | Physical | Bits ko signal (voltage/light/radio) mein badalna | Bit | Cables, 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 ┘
└─────────────┘
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".
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?
| Device | Layer | Kis address pe kaam | Collision domain | Broadcast domain |
|---|---|---|---|---|
| Hub / Repeater | L1 Physical | Kuchh nahi — bas signal repeat | 1 (sab share karte hain) | 1 |
| Bridge / Switch | L2 Data Link | MAC address | Per port 1 (separate) | 1 (VLAN se toda ja sakta hai) |
| Router | L3 Network | IP address | Per port 1 | Per 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?
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.
- 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.
Delay, throughput aur packet loss
Yahan se numericals aate hain — GATE, on-campus test, aur SDE interviews teeno mein.
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)
dtotal = dproc + dqueue + dtrans + dpropdtrans = 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 microsecondsdqueue = variable, congestion pe depend karta 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.
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 = L·a / RL = 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
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.
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.
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:
dend-to-end = N × (L/R) [+ propagation, queuing, processing agar diye ho]
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?
(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.
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?
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)?
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?
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.
- 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.
Application layer aur HTTP
Jahan tumhari app rehti hai. HTTP interview ka sabse favourite protocol hai.
4.1 Application architectures
| Architecture | Kaise kaam karta hai | Pros / Cons | Example |
|---|---|---|---|
| Client–Server | Always-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 P2P | Koi 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 |
| Hybrid | Server sirf lookup/index/login ke liye, data transfer P2P. | Dono ke faayde | Skype (purana), Napster |
4.2 Process communication: socket aur addressing
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).
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?
| Requirement | Matlab | Loss-tolerant app | Loss-sensitive app |
|---|---|---|---|
| Data integrity | 100% reliable delivery chahiye ya nahi | Audio/video streaming | File transfer, web, email |
| Timing / Latency | Low delay chahiye | Games, VoIP: haan (<100 ms). Email: nahi. | |
| Throughput | Minimum bandwidth guarantee | Video: "elastic nahi", minimum chahiye. Email/web: elastic, jitna mile chalega. | |
| Security | Encryption, integrity | TLS 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.
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 connection | Har object ke liye nayi connection, phir band | Ek hi connection pe saare objects |
| Objects per connection | 1 | Multiple |
| OS overhead | Zyada (har connection ke liye buffers/variables) | Kam |
| Slow start penalty | Har baar TCP slow start se shuru | Ek baar window bada ho gaya to fayda |
| Time for N objects | 2·RTT per object | 1·RTT per object (pipelining ke saath ~1 RTT total) |
| Header | — | Connection: keep-alive (1.1 mein default) |
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 × RTTPersistent 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.
(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
| Method | Kaam | Safe? | Idempotent? |
|---|---|---|---|
| GET | Resource fetch karo; parameters URL mein | Haan | Haan |
| POST | Data server ko bhejo (form submit); data body mein | Nahi | Nahi |
| PUT | Resource ko poora replace/upload karo | Nahi | Haan |
| PATCH | Resource ko partially update karo | Nahi | Nahi |
| DELETE | Resource delete karo | Nahi | Haan |
| HEAD | GET jaisa par sirf headers, body nahi (debug/cache check) | Haan | Haan |
| OPTIONS | Server kya-kya support karta hai (CORS preflight) | Haan | Haan |
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
| GET | POST | |
|---|---|---|
| Data kahan | URL query string mein (?a=1&b=2) | Request body mein |
| Length limit | URL length limit (~2000 chars practical) | Practically unlimited |
| Cache/bookmark/history | Ho sakta hai | Nahi |
| Security | URL logs/history mein dikh jaata hai — sensitive data ke liye galat | Better (par bina HTTPS ke dono plaintext hi hain!) |
| Idempotent | Haan | Nahi |
Status codes — ye poochhe jaate hain
| Class | Code | Matlab |
|---|---|---|
| 1xx Info | 100 Continue | Aage bhejo |
| 2xx Success | 200 OK | Sab theek, object attached |
| 201 Created / 204 No Content | Bana diya / kuch return nahi | |
| 3xx Redirect | 301 Moved Permanently | Naya URL, hamesha ke liye |
| 302 / 307 Found / Temporary Redirect | Abhi ke liye kahin aur | |
| 304 Not Modified | Cache valid hai, apni copy use karo (conditional GET ka reply) | |
| 4xx Client error | 400 Bad Request | Request samajh nahi aayi |
| 401 Unauthorized / 403 Forbidden | Login chahiye / access mana hai | |
| 404 Not Found | Document nahi mila | |
| 429 Too Many Requests | Rate limit | |
| 5xx Server error | 500 Internal Server Error | Server crash/bug |
| 502 Bad Gateway / 503 Service Unavailable | Upstream kharab / server down-overloaded | |
| 504 Gateway Timeout | Upstream ne time pe jawab nahi diya |
4.6 Cookies — stateless protocol mein state ★★ common
- Pehli baar tum site pe jaate ho. Server ek unique ID generate karta hai aur backend database mein entry banata hai.
- Response mein header aata hai:
Set-Cookie: 1678 - Browser use apni cookie file mein save kar leta hai (domain ke against).
- Aage har request mein browser bhejta hai:
Cookie: 1678 - Server us ID se tumhe pehchaan leta hai → shopping cart, login session, recommendations.
Cookies ke 4 kaam: authorization, shopping carts, recommendations, user session state.
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 = 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?
(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
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.1 | HTTP/2 | HTTP/3 | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC over UDP |
| Format | Text | Binary framing | Binary |
| Multiplexing | Nahi (pipelining buggy thi) | Haan — ek connection pe multiple streams, frames interleaved | Haan, independent streams |
| App-level HOL | Haan | Solved | Solved |
| Transport-level HOL | Haan | Haan (TCP ki wajah se) | Solved (per-stream loss recovery) |
| Header compression | Nahi | HPACK | QPACK |
| Server push / priority | Nahi | Haan | Haan |
| Handshake RTTs | 1 (TCP) + 2 (TLS) | Same | 1 RTT, ya 0-RTT resume (TCP+TLS merged) |
| Connection migration (WiFi→4G) | Connection toot jaata hai | Toot jaata hai | Connection 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.
- ClientHello — client supported cipher suites aur random number bhejta hai.
- ServerHello + Certificate — server cipher choose karta hai, apna X.509 certificate (public key + CA ka signature) bhejta hai.
- Client CA chain verify karta hai (browser mein pre-installed root CAs se).
- 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).
- Dono taraf symmetric session key derive hoti hai. Actual data symmetric encryption (AES) se hota hai kyunki wo fast hai.
- Finished messages — handshake verify, phir encrypted application data start.
"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?
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:
Secureflag — cookie sirf HTTPS pe jayegi.HttpOnlyflag — 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?
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.
- 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.
DNS — Internet ki phone book
Har interview mein aata hai, aur "google.com type karne pe kya hota hai" ka pehla step yahi hai.
5.1 DNS kya karta hai
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)
- Single point of failure — wo server gira to pura Internet gira.
- Traffic volume — duniya ki saari DNS queries ek server handle nahi kar sakta.
- Distance — India ka user agar US ke server ko query kare to latency bahut zyada.
- 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
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.
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.
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)
| Type | Name | Value | Kaam |
|---|---|---|---|
| A | hostname | IPv4 address | Sabse basic mapping |
| AAAA | hostname | IPv6 address | IPv6 ke liye |
| NS | domain | authoritative server ka hostname | Query ko aage bhejne ke liye |
| CNAME | alias hostname | canonical hostname | Alias → asli naam |
| MX | domain | mail server ka name | Email routing |
| PTR | IP address | hostname | Reverse DNS lookup |
| TXT | domain | arbitrary text | SPF/DKIM (email spam), domain verification |
| SOA | zone | zone info | Zone 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?
Pehli baar (cold cache):
- Host → Local DNS (query) → 1
- Local → Root, Root → Local (referral to .in TLD) → 2
- Local → TLD(.in), TLD → Local (referral to ac.in / bits.ac.in auth) → 2
- Local → Authoritative, Auth → Local (final A record) → 2
- 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?
- 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.
- 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.
Email, FTP aur P2P
SMTP/POP3/IMAP ka difference aur P2P ke distribution-time formulas.
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 | HTTP | |
|---|---|---|
| Direction | Push | Pull |
| Encoding | 7-bit ASCII (MIME se binary) | Binary allowed |
| Multiple objects | Sab ek hi multipart message mein | Har object ka apna response |
| Port | 25 | 80 |
| Common | Dono 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 kahan | Download karke local, server se delete (default) | Server pe hi rehti hai | Server pe |
| Multiple devices | Problem — ek device pe download hui to doosre pe nahi milegi | Perfect — sab devices sync | Perfect |
| Folders | Nahi (stateless across sessions) | Haan, server pe folders/flags (stateful) | Haan |
| Bandwidth/storage | Kam server storage | Zyada server storage | Zyada |
| Partial fetch | Nahi | Haan (sirf header ya ek MIME part) | Haan |
| Protocol | POP3 | IMAP | HTTP/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?
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.
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.
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.
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.
- 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.
Transport layer basics, multiplexing aur UDP
Process-to-process delivery. Yahin se TCP/UDP ka khel shuru hota hai.
7.1 Transport layer ka kaam
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.
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 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 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?
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 │
└───────────────────────────────────────────────┘
- No connection establishment — koi handshake nahi, koi extra RTT nahi (DNS ke liye perfect).
- No connection state — server pe buffers/variables nahi rakhne padte → zyada clients handle kar sakta hai.
- Small header — 8 bytes vs TCP ke 20.
- No congestion control — app jitni tezi se chahe bhej sakti hai (real-time video ke liye achha, network ke liye kabhi kabhi bura).
- 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
- Segment ke contents ko 16-bit integers ki sequence maano.
- Sab ko jodo — 1's complement addition (carry ko wapas LSB pe add karo, "wrap around").
- Result ka 1's complement (sab bits invert) le lo — wahi checksum hai.
- 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.
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.
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
| TCP | UDP | |
|---|---|---|
| Connection | Connection-oriented (3-way handshake) | Connectionless |
| Reliability | Reliable — ACK + retransmission | Unreliable, best effort |
| Ordering | In-order delivery guaranteed | No ordering |
| Header size | 20–60 bytes | 8 bytes |
| Flow control | Haan (receive window) | Nahi |
| Congestion control | Haan (AIMD) | Nahi |
| Speed | Slower (overhead) | Faster |
| Data boundary | Byte-stream (message boundaries preserve nahi hote) | Message/datagram oriented (boundaries preserve) |
| Broadcast/multicast | Nahi (point-to-point only) | Haan |
| Use cases | Web, email, file transfer, SSH, DB | DNS, 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
Server:
socket() → bind() → listen()
→ accept() ← blocks
→ recv()/send() → close()
Client:
socket() → connect()
→ send()/recv() → close()
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.
Reliable Data Transfer: Stop-and-Wait, GBN, Selective Repeat
Ye theory TCP ki neev hai. Window size ke sawaal exams mein pakke aate hain.
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.
| Protocol | Channel assumption | Naya mechanism |
|---|---|---|
| rdt1.0 | Perfectly reliable | Kuch nahi chahiye |
| rdt2.0 | Bit errors ho sakte hain | Checksum + ACK/NAK (ARQ — Automatic Repeat reQuest) |
| rdt2.1 | ACK/NAK bhi corrupt ho sakte hain | Sequence numbers (0,1) — duplicate pakadne ke liye |
| rdt2.2 | Same | NAK hataya — sirf ACK with seq# (duplicate ACK = NAK ka kaam) |
| rdt3.0 | Errors + loss | Timer / timeout + retransmission |
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.
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
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.
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.
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 buffer | Nahi — out-of-order packets discard | Haan — out-of-order buffer karta hai |
| ACK type | Cumulative ACK (ACK n = "n tak sab mil gaya") | Individual ACK har packet ke liye |
| Timer | Ek timer (oldest unACKed packet ka) | Har unACKed packet ka apna timer |
| Loss pe kya | Us packet se aage saare retransmit | Sirf wo packet retransmit |
| Complexity | Simple receiver | Complex (dono taraf buffer + timers) |
| Bandwidth efficiency | Kam (extra retransmissions) | Zyada |
| Window sizes (k-bit seq#) | SWS ≤ 2k − 1, RWS = 1 | SWS = RWS ≤ 2k−1 (yaani 2k/2) |
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?
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?
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?
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.
- 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.
TCP deep dive
Agar sirf ek section padhna ho, to ye. Har interviewer TCP ghumaa-firaake poochhta hai.
9.1 TCP ke characteristics (ek saans mein bolna aana chahiye)
"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 │
└───────────────────────────────────────────────────────────────────────────────┘
| Field | Kaam |
|---|---|
| Sequence number | Is segment ke pehle byte ka byte-stream number (packet number NAHI!) |
| ACK number | Agla expected byte ka number (cumulative ACK) |
| Header length | 4 bits, 32-bit words mein → header 20 se 60 bytes |
| SYN | Connection establish request (sequence number sync) |
| ACK | ACK number field valid hai |
| FIN | Sender ka data khatam, connection close karna hai |
| RST | Connection reset/abort (galat port pe aaya, ya error) |
| PSH | Receiver turant application ko de de (buffer mat karo) |
| URG | Urgent data hai (practically use nahi hota) |
| Receive window | Receiver ke buffer mein kitni jagah khaali hai → flow control |
| Checksum | Header + data + pseudo-header pe error detection |
9.3 Sequence aur ACK numbers ★★★ asked a lot
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?
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) │
Do reasons:
- 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.
- 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) │
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.
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.
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.
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
- 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
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).
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 | Congestion control | |
|---|---|---|
| Kise bachata hai | Receiver ko overflow se | Network (routers) ko overload se |
| Scope | End-to-end, do hosts ke beech | Poore network ka concern |
| Mechanism | rwnd — receiver batata hai | cwnd — sender khud infer karta hai (loss/delay se) |
| Signal | Explicit (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_NODELAYset 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?
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?
- Sequence numbers — ordering aur duplicate detection.
- Cumulative ACKs — receiver confirm karta hai kya mila.
- Checksum — corrupted segment discard.
- Timeout + retransmission — lost segment dobara.
- Fast retransmit (3 dup ACKs) — jaldi recovery.
- Receiver buffering + reordering — out-of-order segments sambhal ke, app ko in-order.
- Flow control — receiver overflow nahi hota (warna data waise hi drop hota).
- 3-way handshake / FIN handshake — connection ki shuruaat aur ant reliable.
- 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).
Congestion control — Tahoe, Reno, AIMD
Numerical yahin se banta hai: "cwnd kis round mein kitna hoga". Ek baar samajh gaye to free marks.
10.1 Congestion kya hai
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)
- 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.
- 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.
- 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
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.
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
LastByteSent − LastByteAcked ≤ min(cwnd, rwnd)Sending rate ≈ cwnd / RTT bytes/sec
cwnd (congestion window) sender khud maintain karta hai. Do phases hain:
| Phase | Kab | cwnd kaise badhta hai | Growth |
|---|---|---|---|
| Slow Start | cwnd < ssthresh | Har ACK pe cwnd += 1 MSS → har RTT mein cwnd double | Exponential |
| Congestion Avoidance | cwnd ≥ ssthresh | Har RTT mein cwnd += 1 MSS (har ACK pe MSS×MSS/cwnd) | Linear (additive increase) |
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
| Event | TCP Tahoe | TCP Reno |
|---|---|---|
| Timeout | ssthresh = cwnd/2; cwnd = 1 MSS; slow start | ssthresh = cwnd/2; cwnd = 1 MSS; slow start |
| 3 duplicate ACKs | ssthresh = cwnd/2; cwnd = 1 MSS; slow start (same as timeout) | ssthresh = cwnd/2; cwnd = ssthresh (+3); fast recovery → seedha congestion avoidance |
| Philosophy | Har loss ko barabar bura maanta hai | 3 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
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.
| Round (RTT) | cwnd (start) | Phase | Note |
|---|---|---|---|
| 1 | 1 | Slow start | cwnd doubles |
| 2 | 2 | Slow start | |
| 3 | 4 | Slow start | |
| 4 | 8 | SS → CA | cwnd = ssthresh(8) → ab linear |
| 5 | 9 | CA | +1 per RTT |
| 6 | 10 | CA | Timeout! ssthresh = 10/2 = 5, cwnd = 1 |
| 7 | 1 | Slow start | |
| 8 | 2 | Slow start | |
| 9 | 4 | Slow start | |
| 10 | 5 | SS → CA | cwnd 8 nahi hoga — ssthresh 5 pe ruk jayega |
| 11 | 6 | CA | |
| 12 | 7 | CA |
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?
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
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
Throughput ≈ 1.22 × MSS / (RTT × √L)
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)
| Algorithm | Idea | Kahan |
|---|---|---|
| TCP CUBIC | Loss 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 TCP | Loss-based + delay-based dono components | Windows |
| BBR | Loss 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 |
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?
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).
- 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.
IP datagram aur fragmentation
Network layer = host-to-host delivery. Har router ismein involved hota hai.
11.1 Network layer ke do plane ★★ common
Local, per-router function. Input port pe aaye datagram ko dekh ke forwarding table se output port pe bhejna. Hardware mein, nanoseconds mein.
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) │
└────────────────────────────────────────────────────────────────┘
| Field | Kaam / yaad rakhne layak baat |
|---|---|
| Version | 4 ya 6 |
| IHL (header length) | 32-bit words mein. Min 5 (= 20 bytes), max 15 (= 60 bytes) |
| Total Length | Header + data, bytes mein. Max 65,535 (practically MTU se limited) |
| Identification | Ek hi original datagram ke saare fragments ka same ID |
| Flags | bit0 reserved, bit1 = DF (Don't Fragment), bit2 = MF (More Fragments) |
| Fragment Offset | Original datagram mein is fragment ka position, 8-byte units mein (isliye fragment size 8 ka multiple hona chahiye) |
| TTL | Har router pe 1 kam; 0 hone pe drop + ICMP Time Exceeded. Infinite looping se bachav. |
| Protocol | Upar wali layer ka protocol: 6 = TCP, 17 = UDP, 1 = ICMP, 89 = OSPF |
| Header checksum | Sirf 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
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.
- Reassembly sirf destination host pe hoti hai, beech ke routers pe nahi. (Kyunki fragments alag-alag raaste le sakte hain.)
- 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.
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
| Fragment | Total length | Data bytes | ID | Offset | MF flag |
|---|---|---|---|---|---|
| 1 | 1500 | 0–1479 | x | 0 | 1 |
| 2 | 1500 | 1480–2959 | x | 185 (=1480/8) | 1 |
| 3 | 1040 | 2960–3979 | x | 370 (=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 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.
IP addressing, subnetting aur CIDR
Sabse zyada numerical yahin se aate hain. Ye section 3 baar padhna, aur khud calculate karna.
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)
| Class | Leading bits | Range (first octet) | Network/Host bits | Networks | Hosts per network |
|---|---|---|---|---|---|
| A | 0 | 1–126 | 8 / 24 | 27 = 128 | 224 − 2 = 16,777,214 |
| B | 10 | 128–191 | 16 / 16 | 214 = 16,384 | 216 − 2 = 65,534 |
| C | 110 | 192–223 | 24 / 8 | 221 | 28 − 2 = 254 |
| D | 1110 | 224–239 | Multicast | ||
| E | 1111 | 240–255 | Reserved/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
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.
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 1Block size (increment) = 256 − (mask ka last non-255 octet)
| CIDR | Subnet mask | Total addresses | Usable hosts | Block size |
|---|---|---|---|---|
| /24 | 255.255.255.0 | 256 | 254 | 256 |
| /25 | 255.255.255.128 | 128 | 126 | 128 |
| /26 | 255.255.255.192 | 64 | 62 | 64 |
| /27 | 255.255.255.224 | 32 | 30 | 32 |
| /28 | 255.255.255.240 | 16 | 14 | 16 |
| /29 | 255.255.255.248 | 8 | 6 | 8 |
| /30 | 255.255.255.252 | 4 | 2 | 4 |
| /16 | 255.255.0.0 | 65,536 | 65,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
| Address | Matlab |
|---|---|
0.0.0.0/8 | "This network" / unspecified (DHCP se pehle) |
127.0.0.0/8 | Loopback — 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/16 | Private addresses (RFC 1918) — Internet pe route nahi hote, NAT ke peeche use hote hain |
169.254.0.0/16 | APIPA / link-local — jab DHCP fail ho jaye |
255.255.255.255 | Limited broadcast (subnet ke bahar nahi jaata) |
224.0.0.0/4 | Multicast |
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?
(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.
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.
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 10101010
| Prefix | Interface |
|---|---|
| 11001000 00010111 00010*** ******** | 0 |
| 11001000 00010111 00011000 ******** | 1 |
| 11001000 00010111 00011*** ******** | 2 |
| otherwise | 3 |
(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.
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)
- 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.
DHCP, NAT, ICMP aur IPv6
Ghar ke router mein ye chaaron roz chal rahe hain. Interview mein DHCP aur NAT pakke aate hain.
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").
- DISCOVER — client broadcast karta hai (src
0.0.0.0:68→ dst255.255.255.255:67) "koi DHCP server hai?" - OFFER — server broadcast se ek IP offer karta hai (transaction ID same rakh ke)
- REQUEST — client ek offer choose karke formally maangta hai (broadcast, taaki baaki servers ko pata chale)
- 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
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 │
└──────────────────────────┴──────────────────────────┘
- 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.
- Reply aata hai destination (138.76.29.7, 5001) pe.
- Router table dekhta hai → destination ko (10.0.0.1, 3345) mein badal ke andar bhej deta hai.
- 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)
- 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.
| Type | Code | Matlab | Kahan dikhta hai |
|---|---|---|---|
| 0 | 0 | Echo reply | ping ka jawab |
| 8 | 0 | Echo request | ping |
| 3 | 0/1/3 | Destination network / host / port unreachable | traceroute ka ant |
| 3 | 4 | Fragmentation needed but DF set | Path MTU discovery |
| 11 | 0 | TTL expired | traceroute ka har hop |
| 4 | 0 | Source quench (congestion control) — ab deprecated | — |
| 5 | 0 | Redirect — "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.
| IPv4 | IPv6 | |
|---|---|---|
| Address size | 32 bits (~4.3 billion) | 128 bits (~3.4×1038) |
| Header size | 20–60 bytes (variable) | 40 bytes fixed |
| Notation | Dotted decimal | Hex, colon-separated: 2001:0db8::1 |
| Checksum | Haan (har hop pe recompute) | Nahi — L2 aur L4 already karte hain, speed badhi |
| Fragmentation | Routers bhi kar sakte hain | Sirf source; router ICMPv6 "Packet Too Big" bhejta hai |
| Options | Header ke andar | Extension headers (chain mein) |
| Broadcast | Haan | Nahi — multicast + anycast se kaam |
| Address config | DHCP/manual | SLAAC (stateless auto-config) bhi |
| Security | Optional | IPsec designed-in |
| Flow label | Nahi | Haan (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?
- 802.11 association — access point se link banti hai (scanning, authentication, association).
- 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:FFpe jaate hain.) - ARP — default gateway ka MAC address pata karne ke liye (kyunki frame bhejne ke liye MAC chahiye).
- DNS query — jab tum koi site kholte ho (UDP 53, gateway ke through local DNS server tak).
- TCP handshake + TLS handshake + HTTP request.
Ye poora sequence Section 22 mein detail mein hai — ye interview ka favourite hai.
- 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.
Router ke andar kya hota hai
Switching fabric, queuing, aur packet scheduling. College exam mein zyada, interview mein occasionally.
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
| Type | Kaise | Limitation |
|---|---|---|
| Memory | Purane routers: packet CPU ke control mein memory mein copy hota hai, phir output port pe | Speed = memory bandwidth / 2 (do baar bus cross karta hai) |
| Bus | Ek shared bus se input se output tak direct | Ek 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
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.
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.
Classic rule (RFC 3439): B = RTT × C (C = link capacity)N flows ke saath (Appenzeller): B = RTT × C / √NBahut bada buffer = bufferbloat (huge delay). Bahut chhota = kam utilization.
14.4 Packet scheduling
| Discipline | Kaise kaam karta hai | Problem |
|---|---|---|
| FCFS / FIFO | Jo pehle aaya wo pehle jayega | Koi differentiation nahi; ek aggressive flow sabko dabaa sakta hai |
| Priority queuing | Traffic classes mein baanto; high-priority queue pehle serve karo (non-preemptive) | Starvation — low priority ko kabhi mauka na mile |
| Round Robin | Har class ki queue se baari-baari ek packet | Sab ko barabar, chahe kisi ko zyada chahiye |
| Weighted Round Robin / WFQ | Har class ko weight wi — usko bandwidth ka wi / Σwj hissa milta hai | Implementation 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 bhejo | Per-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.
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 nahiminth ≤ avg < maxth→ probability p ke saath drop, jo avg ke saath linearly badhti haiavg ≥ 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?
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
- 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.
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.
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.
| Classification | Type A | Type B |
|---|---|---|
| Information | Global — sab routers ko poora topology pata (Link State) | Decentralized — sirf padosiyon ka pata, iterative exchange (Distance Vector) |
| Dynamics | Static — routes dheere badalte hain | Dynamic — link cost/topology change pe jaldi adapt |
| Load sensitivity | Load-sensitive (cost traffic pe depend) — oscillation ka khatra | Load-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.
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.
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.
| Step | N′ (settled) | D(v),p | D(w),p | D(x),p | D(y),p | D(z),p |
|---|---|---|---|---|---|---|
| 0 | u | 5,u | 1,u | 2,u | ∞ | ∞ |
| 1 | uw | 5,u | — | 2,u | ∞ | ∞ |
| 2 | uwx | 4,x | — | — | 3,x | ∞ |
| 3 | uwxy | 4,x | — | — | — | 5,y |
| 4 | uwxyv | — | — | — | — | 5,y |
| 5 | uwxyvz | done | ||||
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):
| Destination | Path | Cost | Outgoing link |
|---|---|---|---|
| v | u→x→v | 4 | (u,x) |
| w | u→w | 1 | (u,w) |
| x | u→x | 2 | (u,x) |
| y | u→x→y | 3 | (u,x) |
| z | u→x→y→z | 5 | (u,x) |
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
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):
- Apna distance vector Dx (har destination ke liye estimate) rakho.
- Padosiyon ko apna DV bhejo.
- Jab kisi padosi ka DV aaye, Bellman-Ford se apna DV update karo.
- 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.
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
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.
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 hai | Poora topology map | Sirf padosiyon se aayi distances |
| Kise batata hai | Sabko (flooding) apne links ke baare mein | Padosiyon ko poori table ke baare mein |
| Message complexity | O(n·E) — n nodes, E links | Sirf padosiyon tak, par convergence time variable |
| Convergence | O(n²) computation, deterministic | Variable, count-to-infinity ho sakti hai |
| Robustness (router kharab ho jaye) | Router sirf apni link cost galat bolega; nodes independently compute karte hain → error localized | Galat DV padosiyon mein phailta hai, poore network mein propagate |
| Memory | Zyada (poora map) | Kam |
| Scalability | Bade networks mein areas mein todna padta hai | Chhote networks ke liye theek |
RIP, OSPF, BGP aur SDN
Intra-AS vs Inter-AS. BGP Internet ko jodne wala "glue" hai.
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:
Goal: performance (shortest/fastest path). Protocols: RIP, OSPF, IS-IS, EIGRP.
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 (
routeddaemon) 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 = 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
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
| Attribute | Kaam |
|---|---|
| AS-PATH | Prefix jin AS se hoke aaya unki list. Loop detection: agar apna ASN dikh jaye to route reject. Chhota AS-PATH generally better. |
| NEXT-HOP | Us router ka IP jisse ye route aaya (AS-PATH ke pehle AS tak pahunchne ke liye) |
| LOCAL PREF | AS 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
- Highest LOCAL PREF (policy decision — sabse important)
- Shortest AS-PATH
- Closest NEXT-HOP router — yehi hot potato routing hai
- Additional criteria (lowest MED, eBGP over iBGP, lowest router ID…)
"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.
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
Har router mein apna routing algorithm chalta hai; control aur data plane ek hi box mein, vendor-specific. Nayi policy lagana mushkil.
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.
- 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.
Link layer services aur error detection
CRC aur Hamming code ke numericals fix aate hain. Do baar khud solve karo.
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).
| Service | Kya karta hai |
|---|---|
| Framing | Datagram ko frame mein daalna — header + trailer lagana |
| Link access (MAC) | Shared medium pe kaun kab bolega, ye decide karna |
| Reliable delivery | Optional — wireless jaise high-error links pe use hota hai (WiFi ACK), fiber pe nahi (waste) |
| Error detection | Parity, checksum, CRC — hardware (NIC) mein |
| Error correction | Kuch links pe (FEC/Hamming) — retransmission se bachne ke liye |
| Flow control | Adjacent nodes ke beech pacing |
| Half/full duplex | Ek 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?
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?
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
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?
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).
- Dono taraf ek generator polynomial G agreed hota hai (r+1 bits).
- Sender data D ke peeche r zeros lagata hai, phir G se modulo-2 division (yaani XOR-based division) karta hai.
- Jo remainder R aaya (r bits), wo zeros ki jagah lagakar bhej deta hai. Ab pura transmitted frame G se exactly divisible hai.
- 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.
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.
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.
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.
Multiple Access protocols
ALOHA efficiency aur CSMA/CD ka minimum frame size — ye do numericals pakke hain.
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).
- Ek node bhej raha hai → usko poora R mile
- M nodes bhej rahe hain → har ek ko R/M mile (average)
- Fully decentralized (koi master node nahi, koi clock sync nahi)
- Simple
18.2 Teen categories
| Category | Protocols | Idea | Problem |
|---|---|---|---|
| Channel partitioning | TDMA, FDMA, CDMA | Channel ko time/frequency/code slots mein baant do | Idle nodes ke slots waste; low load pe inefficient |
| Random access | ALOHA, Slotted ALOHA, CSMA, CSMA/CD, CSMA/CA | Jab bhejna ho bhej do; collision ho to random wait ke baad retry | High load pe collisions se efficiency giri |
| Taking turns | Polling, Token passing | Baari-baari mauka do | Polling 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
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)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.
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.
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
| Method | Channel busy mile to | Trade-off |
|---|---|---|
| 1-persistent | Sunte 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-persistent | Random time wait karo, phir dobara sense karo | Kam collision, par channel idle reh sakta hai (waste) |
| p-persistent | Slotted channel: free hone pe probability p se bhejo, (1−p) se agle slot tak ruko | Beech 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:
- NIC datagram le ke frame banata hai.
- Channel idle hai → bhejna shuru. Busy hai → idle hone tak wait, phir bhejo (1-persistent).
- Poora frame bina collision ke chala gaya → done.
- Collision detect hui → abort karo aur 48-bit jam signal bhejo (taaki sabko pata chal jaye).
- 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.
Ttrans ≥ 2 × Tprop yaani L / R ≥ 2 × d / sLmin = 2 × R × d / s = R × RTT
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?
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.
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
- Half duplex radio — apni transmission itni tez hoti hai ki doosron ka weak signal sunayi hi nahi deta.
- 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.
- 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.
- 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.
Ethernet, switches, VLAN aur MPLS
Switch ka self-learning aur "switch vs router" — dono interview mein pakke hain.
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
- Connectionless — koi handshake nahi sending aur receiving NIC ke beech.
- 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).
- 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 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 / Repeater | Bridge | Switch | Router | |
|---|---|---|---|---|
| Layer | L1 | L2 | L2 | L3 |
| Kaam | Bits ko sab ports pe repeat | 2–4 LAN segments jodta hai, MAC se filter | Multi-port bridge, har port dedicated | Networks jodta hai, IP se forward |
| Table | Nahi | MAC table (self-learning) | MAC/CAM table (self-learning) | Routing/forwarding table (protocols se) |
| Collision domain | Sab ek | Per port | Per port | Per port |
| Broadcast domain | Ek | Ek | Ek (VLAN se todo) | Per port — broadcast rokta hai |
| Simultaneous transmissions | Nahi | Haan | Haan | Haan |
| Configuration | Plug & play | Plug & play | Plug & play (self-learning) | IP config chahiye (manual/DHCP) |
19.4 Switch self-learning ★★★ asked a lot
- Learn: Jab frame aaye, uska source MAC aur incoming port table mein daal do (TTL ke saath, typically 60 sec).
- 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.)
- 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.
(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.
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).
ARP — IP se MAC tak
Chhota topic, par interview mein har baar aata hai. Walk-through zaroor yaad karo.
20.1 ARP kya karta hai ★★★ asked a lot
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.
- 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?" - LAN ke saare nodes wo frame receive karte hain.
- Jiska IP match karta hai (B), wo unicast mein ARP reply bhejta hai apne MAC ke saath.
- A apni ARP table mein entry cache kar leta hai (TTL tak).
"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."
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 │
└────────┘ └──────────────────┘ └────────┘
- A apna IP datagram banata hai: source IP = A, destination IP = B. (Ye poore safar mein nahi badlega.)
- A dekhta hai (apne subnet mask se) ki B doosre subnet mein hai → to frame default gateway (R1) ko bhejna hoga.
- A ko R1 ka MAC chahiye → ARP (agar cache mein nahi hai). R1 apna MAC bhej deta hai.
- A frame banata hai: src MAC = A, dest MAC = R1, payload mein IP datagram (A → B).
- 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.
- R ko B ka MAC chahiye → ARP subnet 2 pe. B apna MAC deta hai.
- R naya frame banata hai: src MAC = R2, dest MAC = B, wahi IP datagram andar.
- B frame receive karta hai, datagram nikaal ke upar transport layer ko de deta 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?
ping 8.8.8.8 karne pe:
- Host dekhta hai 8.8.8.8 doosre subnet mein hai → default gateway chahiye.
- ARP — gateway ka MAC pata karo (agar cache mein nahi).
- ICMP Echo Request banega → IP datagram mein wrap → Ethernet frame mein (dest MAC = gateway).
- Router se router hop karte hue destination tak (har hop pe naya L2 frame, TTL−1).
- Destination ICMP Echo Reply bhejta hai.
- Host RTT calculate karta hai.
Agar ping google.com karo to sabse pehle ek DNS query (UDP 53) bhi hogi.
- 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.
Wireless basics aur network security
Slides mein kam hai par interviews mein aata hai — isliye compact version.
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).
(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
| Goal | Matlab | Mechanism |
|---|---|---|
| Confidentiality | Sirf intended receiver padh sake | Encryption (AES, RSA) |
| Integrity | Message beech mein badla na ho | Hash + MAC (HMAC), digital signature |
| Authentication | Doosra banda wahi hai jo bolta hai | Certificates, nonce challenge, passwords |
| Availability / Access control | Service chalti rahe, sirf authorized log use karein | Firewalls, rate limiting, DDoS protection |
Symmetric vs Asymmetric encryption
| Symmetric (AES, DES) | Asymmetric / Public key (RSA, ECC) | |
|---|---|---|
| Keys | Ek hi shared secret key | Public key (sabke liye) + private key (sirf owner) |
| Speed | Bahut fast | Slow (100–1000× slower) |
| Problem | Key exchange kaise karein? | Slow, bade data ke liye impractical |
| Use | Actual data encryption | Key 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)
| Attack | Kya hota hai | Bachav |
|---|---|---|
| Packet sniffing | Shared medium pe promiscuous mode se sab padhna | Encryption (TLS/WPA2) |
| IP spoofing | Fake source IP se packet bhejna | Ingress filtering, authentication |
| MITM | Beech mein baith ke padhna/badalna | TLS + certificate verification |
| DoS / DDoS | Bandwidth/connection resources bhar dena (botnet se) | Rate limiting, filtering, scrubbing services, anycast |
| SYN flood | Half-open connections se server ki table bharna | SYN cookies |
| ARP spoofing | Fake ARP reply se traffic apni taraf mod lena | Dynamic ARP Inspection, static entries |
| DNS cache poisoning | Resolver ko fake mapping cache karwa dena | DNSSEC, random query IDs + source ports |
| BGP hijacking | Galat prefix advertise karke traffic kheenchna | RPKI, 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.
"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.
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)
- Browser URL parse karta hai; cache check karta hai.
- DNS se google.com ka IP nikalta hai.
- Us IP ke saath TCP 3-way handshake (port 443).
- TLS handshake — certificate verify, session key.
- HTTP GET request jaati hai, server response deta hai.
- Browser HTML parse karta hai, aur objects (CSS/JS/images) ke liye aur requests bhejta hai.
- 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/hostsbhi) → router cache → ISP resolver cache. - Miss hone par local DNS resolver iterative queries karta hai: root →
.comTLD → 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).
| Layer | Kya hua |
|---|---|
| Application | DNS, HTTP, TLS |
| Transport | UDP (DNS), TCP (handshake, reliability, flow/congestion control), ports |
| Network | IP addressing, routing (LPM), TTL, NAT, ICMP (errors), fragmentation |
| Link | ARP, Ethernet/WiFi framing, MAC addresses, CSMA/CA, switch forwarding |
| Physical | Bits over WiFi radio / copper / fiber |
Follow-up: "Page slow load ho raha hai — tum kaise debug karoge?" (system-design flavour)
Layer by layer chalo — ye structured approach interviewer ko pasand aata hai:
- Physical/Link: WiFi signal, packet loss —
pingse loss % dekho. - Network:
traceroute— kis hop pe latency spike ho raha hai? Koi routing loop? - DNS:
dig/nslookupse resolution time — DNS slow to pehla byte hi late aayega. - Transport: RTT zyada? Packet loss se congestion window chhoti reh rahi hai? Wireshark se retransmissions dekho.
- 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.
- Fixes: CDN, caching headers, compression (gzip/brotli), fewer round trips, connection reuse, HTTP/3.
Rapid-fire interview Q&A (50)
Har question ka answer 20–40 seconds mein bolna hai. Pehle khud bolo, phir kholo.
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.
Numerical problem bank
Mixed problems, koi hint nahi ki kis topic ka hai — asli exam aisa hi hota hai. Pen-paper nikalo.
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.
| Event | cwnd (baad mein) | ssthresh | Phase |
|---|---|---|---|
| Start | 16 | 16 | CA |
| 3 dup ACKs | 8 | 8 | Fast recovery → CA |
| +1 RTT | 9 | 8 | CA |
| +2 RTT | 10 | 8 | CA |
| +3 RTT | 11 | 8 | CA |
| +4 RTT → timeout | 1 | 6 (=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.
| Subnet | Network | Host range | Broadcast |
|---|---|---|---|
| 1 | 192.168.1.0/26 | .1 – .62 | 192.168.1.63 |
| 2 | 192.168.1.64/26 | .65 – .126 | 192.168.1.127 |
| 3 | 192.168.1.128/26 | .129 – .190 | 192.168.1.191 |
| 4 | 192.168.1.192/26 | .193 – .254 | 192.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?
| Prefix | Next hop |
|---|---|
| 200.100.0.0/16 | A |
| 200.100.48.0/20 | B |
| 200.100.50.0/24 | C |
| 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.
| # | Direction | Flags | Seq | ACK |
|---|---|---|---|---|
| 1 | C → S | SYN | 5000 | — |
| 2 | S → C | SYN, ACK | 9000 | 5001 |
| 3 | C → S | ACK | 5001 | 9001 |
| 4 | C → S | ACK + 1000 bytes data | 5001 | 9001 |
| 5 | S → C | ACK | 9001 | 6001 |
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.
| Step | Settled | B | C | D | E | F |
|---|---|---|---|---|---|---|
| 0 | A | 4,A | 2,A | ∞ | ∞ | ∞ |
| 1 | A,C | 3,C | — | 10,C | 12,C | ∞ |
| 2 | A,C,B | — | — | 8,B | 12,C | ∞ |
| 3 | A,C,B,D | — | — | — | 10,D | 14,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.
Cheat sheet — ek page pe sab kuch
Interview se 1 ghanta pehle sirf ye section padhna. Print karke rakh lo.
25.1 Formula sheet
| Topic | Formula |
|---|---|
| Total delay | d = dproc + dqueue + dtrans + dprop |
| Transmission delay | L / R |
| Propagation delay | d / s (s ≈ 2×108 m/s) |
| Traffic intensity | L·a / R (→1 pe delay blow up) |
| Throughput | min(R1, …, Rn) — bottleneck |
| Store & forward, N links | N · L/R; P packets: (N + P − 1) · L/R |
| Stop-and-wait utilization | (L/R) / (RTT + L/R) |
| Pipelined utilization | N·(L/R) / (RTT + L/R) |
| Window for full utilization | N ≥ (RTT + L/R)/(L/R); BDP = R × RTT |
| GBN / SR window limit | 2k − 1 / 2k−1 |
| TCP timeout | EstRTT + 4·DevRTT; EstRTT = 0.875·old + 0.125·sample |
| TCP throughput | 0.75·W/RTT or 1.22·MSS/(RTT·√L) |
| Sender limit | LastByteSent − LastByteAcked ≤ min(cwnd, rwnd) |
| Subnet: hosts | 2(32−x) − 2; block size = 256 − mask octet |
| Fragment offset | byte position / 8; payload 8 ka multiple |
| Pure / Slotted ALOHA | S = G·e−2G (max 18.4%) / S = G·e−G (max 36.8%) |
| Slotted ALOHA success | N·p·(1−p)N−1, optimal p = 1/N |
| CSMA/CD min frame | Lmin = R × 2·Tprop |
| CSMA/CD efficiency | 1 / (1 + 5·tprop/ttrans) |
| Hamming parity bits | 2r ≥ m + r + 1 |
| P2P vs CS distribution | Dcs = max(NF/us, F/dmin); Dp2p = max(F/us, F/dmin, NF/(us+Σui)) |
25.2 Port numbers
| Port | Protocol | Transport | Port | Protocol | Transport |
|---|---|---|---|---|---|
| 20/21 | FTP data/control | TCP | 110 | POP3 | TCP |
| 22 | SSH / SFTP | TCP | 143 | IMAP | TCP |
| 23 | Telnet | TCP | 161/162 | SNMP | UDP |
| 25 | SMTP | TCP | 179 | BGP | TCP |
| 53 | DNS | UDP (TCP for large/AXFR) | 443 | HTTPS / QUIC | TCP / UDP |
| 67/68 | DHCP server/client | UDP | 520 | RIP | UDP |
| 69 | TFTP | UDP | 3306 | MySQL | TCP |
| 80 | HTTP | TCP | 3389 | RDP | TCP |
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)
25.4 Protocol → layer map
| Layer | Protocols |
|---|---|
| Application | HTTP(S), DNS, SMTP, POP3, IMAP, FTP, SSH, Telnet, DHCP, SNMP, BitTorrent, QUIC |
| Transport | TCP, UDP, SCTP |
| Network | IPv4, IPv6, ICMP, IGMP, OSPF, RIP*, BGP*, IPsec |
| Data Link | Ethernet (802.3), WiFi (802.11), ARP, PPP, STP, VLAN (802.1Q), MPLS (2.5) |
| Physical | Cables, 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
| Pair | Ek line ka farak |
|---|---|
| TCP vs UDP | Reliable + ordered + controlled vs fast + lightweight + no guarantees |
| Flow vs congestion control | Receiver bachao (rwnd, explicit) vs network bachao (cwnd, implicit) |
| Routing vs forwarding | Path decide karna (global) vs packet ko port pe bhejna (local) |
| Switch vs router | MAC/L2/self-learning vs IP/L3/routing protocol |
| MAC vs IP | Flat + permanent + per-link vs hierarchical + assigned + end-to-end |
| GBN vs SR | Cumulative ACK + retransmit all vs individual ACK + retransmit one |
| Tahoe vs Reno | 3 dup ACK pe cwnd = 1 vs cwnd = ssthresh (fast recovery) |
| LS vs DV | Poora topology + Dijkstra vs padosiyon ke vectors + Bellman-Ford |
| Intra-AS vs Inter-AS | Performance (OSPF/RIP) vs policy (BGP) |
| POP3 vs IMAP | Download-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/CA | Wired: collision detect + abort vs Wireless: avoid + ACK + RTS/CTS |
| Circuit vs packet switching | Reserved dedicated vs shared statistical multiplexing |
| Symmetric vs asymmetric crypto | Fast + shared key vs slow + public/private key pair |
Revision plan aur checklist
Kitna time hai uske hisaab se plan chuno.
26.1 Agar 3 din hain
| Din | Kya | Sections |
|---|---|---|
| Day 1 | Foundations + Application layer. Din ke ant mein Section 22 ek baar padhna. | 01, 02, 03, 04, 05, 06 |
| Day 2 | Transport layer — sabse heavy din. Saare numericals khud solve karo. | 07, 08, 09, 10 |
| Day 3 | Network + 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)
- Section 25 (cheat sheet) — 20 min, sab formulas aur comparisons.
- Section 23 (50 rapid-fire) — 60 min, har question loud bolke answer karo.
- Section 22 (google.com walkthrough) — 20 min, ye zaroor aayega.
- Sections 09, 10, 12, 20 — TCP, congestion control, subnetting, ARP. 2 ghante.
- Section 24 se 5–6 numericals solve karo. 1 ghanta.
26.3 Final checklist — tick karke jao
- 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)
- 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.
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.
Ctrl+P se print karo (khule hue solutions hi print honge — pehle "⊕ all" dabao).