# Networking Fundamentals 

## Table of Contents
1. [OSI & TCP/IP Models](#osi--tcpip-models)
2. [IP Addressing & Subnetting](#ip-addressing--subnetting)
3. [DNS](#dns)
4. [Routing](#routing)
5. [Load Balancing](#load-balancing)
6. [Firewalls & Security](#firewalls--security)
7. [VPN & Tunneling](#vpn--tunneling)
8. [Service Mesh](#service-mesh)
9. [Troubleshooting Tools](#troubleshooting-tools)
10. [Interview Scenarios](#interview-scenarios)

---

## OSI & TCP/IP Models

### 1. OSI Model (7 Layers)
```
Layer 7 - Application:  HTTP, FTP, SMTP, DNS
Layer 6 - Presentation: SSL/TLS, encryption
Layer 5 - Session:      Session management, API calls
Layer 4 - Transport:    TCP, UDP
Layer 3 - Network:      IP, ICMP, routing
Layer 2 - Data Link:    Ethernet, MAC addresses, switches
Layer 1 - Physical:     Cables, hubs, signals
```

### 2. TCP/IP Model (4 Layers)
```
Application Layer:     HTTP, FTP, DNS, SSH (OSI 5-7)
Transport Layer:       TCP, UDP (OSI 4)
Internet Layer:        IP, ICMP, ARP (OSI 3)
Network Access Layer:  Ethernet, WiFi (OSI 1-2)
```

### 3. Protocols by Layer
```
Application (L7):
- HTTP/HTTPS (80/443)
- SSH (22)
- FTP (20/21)
- SMTP (25)
- DNS (53)
- DHCP (67/68)

Transport (L4):
- TCP: Connection-oriented, reliable, ordered, flow control
- UDP: Connectionless, fast, no guarantees, for streaming/gaming

Network (L3):
- IPv4: 32-bit addresses (e.g., 192.168.1.1)
- IPv6: 128-bit addresses (e.g., 2001:db8::1)
- ICMP: Ping, traceroute

Data Link (L2):
- Ethernet: MAC addresses (48-bit, e.g., AA:BB:CC:DD:EE:FF)
- ARP: Maps IP to MAC addresses
```

---

## IP Addressing & Subnetting

### 4. IPv4 Addressing
```
Classes (legacy):
Class A: 1.0.0.0 - 126.255.255.255    (16M hosts per network)
Class B: 128.0.0.0 - 191.255.255.255  (65K hosts per network)
Class C: 192.0.0.0 - 223.255.255.255  (254 hosts per network)

Private ranges (RFC 1918):
10.0.0.0/8        (10.0.0.0 - 10.255.255.255)
172.16.0.0/12     (172.16.0.0 - 172.31.255.255)
192.168.0.0/16    (192.168.0.0 - 192.168.255.255)

Special addresses:
127.0.0.1         Loopback
0.0.0.0           Default route
255.255.255.255   Broadcast
```

### 5. CIDR Notation
```
192.168.1.0/24
- Network: 192.168.1.0
- Subnet mask: 255.255.255.0
- Usable IPs: 192.168.1.1 - 192.168.1.254 (254 hosts)
- Broadcast: 192.168.1.255

Common CIDR blocks:
/32 - 1 IP       (255.255.255.255)
/31 - 2 IPs      (point-to-point links)
/30 - 4 IPs      (2 usable)
/29 - 8 IPs      (6 usable)
/28 - 16 IPs     (14 usable)
/27 - 32 IPs     (30 usable)
/26 - 64 IPs     (62 usable)
/25 - 128 IPs    (126 usable)
/24 - 256 IPs    (254 usable) - Class C
/16 - 65,536 IPs - Class B
/8  - 16M IPs    - Class A
```

### 6. Subnetting Examples
```
Network: 192.168.1.0/24
Divide into 4 subnets:

Subnet 1: 192.168.1.0/26   (.0 - .63)    - 62 hosts
Subnet 2: 192.168.1.64/26  (.64 - .127)  - 62 hosts
Subnet 3: 192.168.1.128/26 (.128 - .191) - 62 hosts
Subnet 4: 192.168.1.192/26 (.192 - .255) - 62 hosts

VPC example (AWS/Azure):
VPC: 10.0.0.0/16
- Public Subnet AZ-A:  10.0.1.0/24
- Private Subnet AZ-A: 10.0.10.0/24
- Public Subnet AZ-B:  10.0.2.0/24
- Private Subnet AZ-B: 10.0.20.0/24
```

---

## DNS

### 7. DNS Record Types
```
A      - IPv4 address        example.com     -> 93.184.216.34
AAAA   - IPv6 address        example.com     -> 2606:2800:220:1:248:1893:25c8:1946
CNAME  - Canonical name      www.example.com -> example.com
MX     - Mail exchange       example.com     -> mail.example.com (priority 10)
TXT    - Text record         example.com     -> "v=spf1 include:_spf.google.com ~all"
NS     - Nameserver          example.com     -> ns1.example.com
SOA    - Start of authority  example.com     -> ns1.example.com admin.example.com
PTR    - Reverse lookup      34.216.184.93.in-addr.arpa -> example.com
SRV    - Service record      _http._tcp.example.com -> server.example.com:80
CAA    - Certificate auth    example.com     -> 0 issue "letsencrypt.org"
```

### 8. DNS Commands
```bash
# Query DNS
nslookup example.com
nslookup example.com 8.8.8.8

# Dig (detailed)
dig example.com
dig example.com A
dig example.com MX
dig example.com ANY
dig @8.8.8.8 example.com

# Reverse lookup
dig -x 93.184.216.34

# Trace query path
dig example.com +trace

# Short answer
dig example.com +short

# host command
host example.com
host -t MX example.com

# Check DNS propagation
dig example.com @8.8.8.8
dig example.com @1.1.1.1
```

### 9. DNS Resolution Flow
```
1. Browser cache
2. OS cache (localhost)
3. Router cache
4. ISP DNS cache
5. Root nameserver (.)
6. TLD nameserver (.com)
7. Authoritative nameserver (example.com)
8. Response back through chain

DNS TTL (Time To Live):
- Determines cache duration
- Low TTL (60s): Fast updates, more queries
- High TTL (86400s): Less load, slower updates
```

---

## Routing

### 10. Routing Basics
```
Default gateway: Router for external networks
Static route:    Manually configured
Dynamic route:   Learned via routing protocols

Routing table example:
Destination     Gateway         Interface
0.0.0.0/0       192.168.1.1     eth0       (default route)
192.168.1.0/24  0.0.0.0         eth0       (local network)
10.0.0.0/8      192.168.1.254   eth0       (specific route)
```

### 11. Linux Routing Commands
```bash
# Show routing table
ip route show
route -n

# Add static route
sudo ip route add 10.0.0.0/8 via 192.168.1.254
sudo route add -net 10.0.0.0/8 gw 192.168.1.254

# Delete route
sudo ip route del 10.0.0.0/8
sudo route del -net 10.0.0.0/8

# Add default gateway
sudo ip route add default via 192.168.1.1
sudo route add default gw 192.168.1.1

# Show ARP table
ip neigh show
arp -n

# Flush route cache
sudo ip route flush cache
```

### 12. Routing Protocols
```
Static Routing:
- Manually configured
- No overhead, predictable
- Doesn't scale, no failover

Dynamic Routing:
RIP (Routing Information Protocol):
- Distance vector
- Max 15 hops
- Simple, legacy

OSPF (Open Shortest Path First):
- Link state
- Fast convergence
- Scalable, hierarchical

BGP (Border Gateway Protocol):
- Path vector
- Internet routing
- Policy-based, AS routing

AWS/Azure routing:
- Route tables per subnet
- Virtual network peering
- VPN/Direct Connect routing
```

---

## Load Balancing

### 13. Load Balancer Types
```
Layer 4 (Transport Layer):
- TCP/UDP load balancing
- Fast, low latency
- No content inspection
- Example: AWS NLB, HAProxy TCP mode

Layer 7 (Application Layer):
- HTTP/HTTPS load balancing
- Content-based routing (URL, headers, cookies)
- SSL termination
- Example: AWS ALB, Nginx, HAProxy HTTP mode
```

### 14. Load Balancing Algorithms
```
Round Robin:
- Distributes requests evenly
- Simple, works if backends equal

Least Connections:
- Sends to backend with fewest connections
- Good for long-lived connections

IP Hash:
- Hash client IP to determine backend
- Session persistence
- Same client -> same backend

Weighted Round Robin:
- Assign weights to backends
- Direct more traffic to powerful servers

Least Response Time:
- Monitor backend latency
- Route to fastest backend
```

### 15. Health Checks
```
TCP check:
- Connect to port
- Fast, simple
- Doesn't verify app health

HTTP check:
- GET /health endpoint
- Check status code (200 OK)
- Can verify application logic

Example health check endpoint:
GET /health
Response:
{
  "status": "healthy",
  "database": "connected",
  "cache": "connected",
  "uptime": 3600
}
```

---

## Firewalls & Security

### 16. iptables (Linux Firewall)
```bash
# List rules
sudo iptables -L
sudo iptables -L -n -v

# Allow SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP/HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow established connections
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Drop all other incoming
sudo iptables -P INPUT DROP

# Allow outgoing
sudo iptables -P OUTPUT ACCEPT

# Delete rule
sudo iptables -D INPUT 1

# Save rules
sudo iptables-save > /etc/iptables/rules.v4

# Flush all rules
sudo iptables -F
```

### 17. Cloud Security Groups
```
AWS Security Group:
Type        Protocol  Port Range  Source
SSH         TCP       22          0.0.0.0/0
HTTP        TCP       80          0.0.0.0/0
HTTPS       TCP       443         0.0.0.0/0
Custom TCP  TCP       8080        sg-12345678 (other SG)
All ICMP    ICMP      N/A         10.0.0.0/16

Azure Network Security Group (NSG):
Priority  Name       Port  Protocol  Source      Action
100       AllowSSH   22    TCP       Internet    Allow
200       AllowHTTP  80    TCP       Internet    Allow
300       AllowHTTPS 443   TCP       Internet    Allow
65000     DenyAll    *     *         *           Deny
```

### 18. Network Security Best Practices
```
Defense in Depth:
1. Perimeter firewall
2. Network segmentation
3. Host-based firewall
4. Application firewall (WAF)

Zero Trust:
- Never trust, always verify
- Least privilege access
- Microsegmentation
- Continuous monitoring

Security zones:
DMZ:       Public-facing (web servers)
Internal:  Application servers
Database:  Data tier (most restricted)
Management: Bastion/jump hosts
```

---

## VPN & Tunneling

### 19. VPN Types
```
Site-to-Site VPN:
- Connect two networks
- Office &lt;-> Cloud
- Always-on connection
- IPsec protocol

Point-to-Site VPN:
- Individual client to network
- Remote workers
- On-demand connection
- OpenVPN, WireGuard

SSL/TLS VPN:
- Browser-based
- No client software
- Limited functionality
```

### 20. SSH Tunneling
```bash
# Local port forwarding
# Access remote service locally
ssh -L 8080:localhost:80 user@remote-server
# Access http://localhost:8080 -> remote-server:80

# Remote port forwarding
# Expose local service to remote
ssh -R 9090:localhost:3000 user@remote-server
# Remote users access remote-server:9090 -> your localhost:3000

# Dynamic port forwarding (SOCKS proxy)
ssh -D 1080 user@remote-server
# Configure browser to use localhost:1080 as proxy

# Tunnel through bastion host
ssh -J bastion-user@bastion-host user@private-server
ssh -o ProxyJump=bastion-user@bastion-host user@private-server
```

---

## Service Mesh

### 21. Service Mesh Concepts
```
Istio/Linkerd features:
- Service discovery
- Load balancing
- Mutual TLS (mTLS)
- Circuit breaking
- Retry logic
- Traffic splitting (canary)
- Observability (traces, metrics)

Components:
Data plane:  Envoy proxy sidecars
Control plane: Istiod (Istio) / controller (Linkerd)

Traffic management:
VirtualService: Route rules (match, weight, timeout)
DestinationRule: Load balancing, circuit breaker
Gateway: Ingress/egress
```

### 22. Istio Traffic Split
```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: myapp
spec:
  hosts:
  - myapp
  http:
  - match:
    - headers:
        user:
          exact: beta-tester
    route:
    - destination:
        host: myapp
        subset: v2
  - route:
    - destination:
        host: myapp
        subset: v1
      weight: 90
    - destination:
        host: myapp
        subset: v2
      weight: 10
```

---

## Troubleshooting Tools

### 23. Network Connectivity
```bash
# Ping
ping -c 4 example.com
ping -c 4 8.8.8.8

# Traceroute
traceroute example.com
mtr example.com  # Better traceroute

# Telnet (test port)
telnet example.com 80
telnet 192.168.1.1 22

# nc (netcat) - test port
nc -zv example.com 80
nc -zv 192.168.1.1 22-25  # Port range

# Check open ports
sudo netstat -tulnp
sudo ss -tulnp
sudo lsof -i -P -n
```

### 24. DNS & HTTP Tools
```bash
# curl with timing
curl -w "@curl-format.txt" -o /dev/null -s https://example.com

# curl-format.txt:
time_namelookup:  %{time_namelookup}s
time_connect:     %{time_connect}s
time_appconnect:  %{time_appconnect}s
time_pretransfer: %{time_pretransfer}s
time_starttransfer: %{time_starttransfer}s
time_total:       %{time_total}s
http_code:        %{http_code}

# wget
wget https://example.com/file.zip

# Check SSL certificate
openssl s_client -connect example.com:443
echo | openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -noout -dates
```

### 25. Packet Analysis
```bash
# tcpdump
sudo tcpdump -i eth0
sudo tcpdump -i eth0 port 80
sudo tcpdump -i eth0 host 192.168.1.100
sudo tcpdump -i eth0 -w capture.pcap

# Wireshark (GUI)
wireshark &

# Read pcap file
tcpdump -r capture.pcap
```

---

## Interview Scenarios

### Scenario 1: Troubleshoot Connectivity Issue
```bash
# Problem: Can't connect to web server

# 1. Check local network
ip addr show
ip route show
ping 192.168.1.1  # Gateway

# 2. Check DNS
nslookup example.com
dig example.com +short

# 3. Check routing
traceroute example.com
mtr example.com

# 4. Check port
telnet example.com 80
nc -zv example.com 80

# 5. Check firewall
sudo iptables -L -n
# AWS: Check security group rules

# 6. Check service
sudo netstat -tulnp | grep :80
sudo systemctl status nginx

# 7. Test HTTP
curl -v http://example.com
```

### Scenario 2: Design HA Architecture
```
3-Tier Web Application:

Internet
    |
[Internet Gateway]
    |
[Application Load Balancer] (Multi-AZ)
    |
    +--- Public Subnet AZ-A (10.0.1.0/24)
    |        |
    |        +--- NAT Gateway
    |
    +--- Public Subnet AZ-B (10.0.2.0/24)
             |
             +--- NAT Gateway
    
Private Subnet AZ-A (10.0.10.0/24)
    |
    +--- Web Server 1 (Auto Scaling Group)
    +--- Web Server 2
    
Private Subnet AZ-B (10.0.20.0/24)
    |
    +--- Web Server 3 (Auto Scaling Group)
    +--- Web Server 4

Database Subnet AZ-A (10.0.100.0/24)
    |
    +--- RDS Primary

Database Subnet AZ-B (10.0.200.0/24)
    |
    +--- RDS Standby

Route Tables:
- Public: 0.0.0.0/0 -> Internet Gateway
- Private: 0.0.0.0/0 -> NAT Gateway

Security:
- ALB SG: Allow 80/443 from 0.0.0.0/0
- Web SG: Allow 8080 from ALB SG
- DB SG: Allow 3306 from Web SG
```

### Scenario 3: Implement Network Segmentation
```
Network: 10.0.0.0/16

Segmentation:
1. DMZ (Public):          10.0.1.0/24
   - Load balancers
   - Bastion hosts
   
2. Application (Private): 10.0.10.0/24
   - Web servers
   - Application servers
   
3. Database (Restricted): 10.0.100.0/24
   - Database servers
   - Cache servers
   
4. Management:            10.0.200.0/24
   - Monitoring
   - Logging
   - CI/CD

Firewall rules:
Internet -> DMZ: Allow 80, 443
DMZ -> App: Allow 8080
App -> Database: Allow 3306, 6379
Management -> All: Allow 22 (SSH)
All -> Management: Allow 9090 (Prometheus), 514 (syslog)
```

---


**Total Concepts**: 60+ networking fundamentals
