🌐 Complete Networking Guide
Comprehensive reference covering network protocols, server administration, security, and troubleshooting.
📡 Network Fundamentals
🌐 OSI Model
7-layer network architecture
🔗 TCP/IP Model
4-layer practical model
🔄 Protocols
Communication rules
🛡️ Security
Network protection
📊 OSI Model Layers
| Layer | Name | Function | Protocols/Devices |
|---|---|---|---|
| 7 | Application | User interface, network services | HTTP, FTP, SMTP, DNS |
| 6 | Presentation | Data formatting, encryption | SSL, TLS, JPEG, MPEG |
| 5 | Session | Connection establishment, management | NetBIOS, RPC, SIP |
| 4 | Transport | End-to-end communication, reliability | TCP, UDP, SCTP |
| 3 | Network | Logical addressing, routing | IP, ICMP, OSPF, Router |
| 2 | Data Link | Physical addressing, error detection | Ethernet, MAC, Switch, Bridge |
| 1 | Physical | Electrical signals, physical connections | RJ45, Fiber, Hub, Repeater |
💻 Network Programming Languages
🐍 Python
Strengths
- Extensive networking libraries (socket, asyncio, requests)
- Rapid prototyping and development
- Large ecosystem (Scapy for packet manipulation, Paramiko for SSH)
- Cross-platform compatibility
- Excellent for automation and scripting
Common Uses
- Network automation (Netmiko, NAPALM)
- Packet analysis and manipulation
- Web servers (Django, Flask)
- API development and consumption
- Network monitoring and diagnostics
Example: Basic Python Socket Server
import socket
import threading
def handle_client(client_socket, address):
print(f"[+] Connection from {address}")
client_socket.send(b"Welcome to the server!\n")
while True:
data = client_socket.recv(1024)
if not data:
break
print(f"[{address}] {data.decode()}")
client_socket.send(b"Message received\n")
client_socket.close()
def start_server(host='0.0.0.0', port=9999):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(5)
print(f"[*] Listening on {host}:{port}")
while True:
client, addr = server.accept()
client_handler = threading.Thread(target=handle_client, args=(client, addr))
client_handler.start()
if __name__ == "__main__":
start_server()
☕ Java
Strengths
- Built-in networking APIs in standard library
- Platform independence (JVM)
- Strong typing and object-oriented design
- Excellent for enterprise applications
- Robust concurrency support
Common Uses
- Enterprise web applications
- Android network applications
- High-performance servers
- Distributed systems
- Middleware and messaging systems
Example: Java HTTP Server
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.*;
import java.net.InetSocketAddress;
public class SimpleHttpServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = "<html><body><h1>Java HTTP Server</h1>" +
"<p>Request Method: " + exchange.getRequestMethod() + "</p>" +
"<p>Remote Address: " + exchange.getRemoteAddress() + "</p>" +
"</body></html>";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
server.createContext("/api", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = "{\"status\": \"ok\", \"message\": \"API endpoint\"}";
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
server.setExecutor(null);
server.start();
System.out.println("Server started on port 8080");
}
}
🚀 Go (Golang)
Strengths
- Built-in concurrency with goroutines
- Excellent standard library for networking
- Fast compilation and execution
- Statically linked binaries (no dependencies)
- Designed for cloud and network services
Common Uses
- High-performance web servers
- Microservices and APIs
- Network proxies and load balancers
- Command-line network tools
- Container and orchestration tools (Docker, Kubernetes)
Example: Go Concurrent TCP Server
package main
import (
"bufio"
"fmt"
"net"
"strings"
"time"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
remoteAddr := conn.RemoteAddr().String()
fmt.Printf("New connection from %s\n", remoteAddr)
conn.Write([]byte("Welcome to Go TCP Server!\n"))
conn.Write([]byte("Type 'quit' to exit\n"))
reader := bufio.NewReader(conn)
for {
conn.SetDeadline(time.Now().Add(60 * time.Second))
message, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("Connection closed: %s\n", remoteAddr)
return
}
message = strings.TrimSpace(message)
fmt.Printf("[%s] %s\n", remoteAddr, message)
if strings.ToLower(message) == "quit" {
conn.Write([]byte("Goodbye!\n"))
return
}
response := fmt.Sprintf("Echo: %s\n", message)
conn.Write([]byte(response))
}
}
func main() {
listener, err := net.Listen("tcp", ":9999")
if err != nil {
fmt.Println("Error starting server:", err)
return
}
defer listener.Close()
fmt.Println("TCP Server listening on :9999")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleConnection(conn)
}
}
🐚 Bash/Shell Scripting
Strengths
- Direct access to system networking tools
- Excellent for automation and cron jobs
- Lightweight and fast execution
- Ideal for system administration tasks
- Pipeline processing of network data
Common Uses
- Network monitoring scripts
- Firewall rule management
- Log analysis and processing
- Backup and synchronization
- Service health checks
Example: Network Monitor Script
#!/bin/bash
# Network Monitoring Script
LOG_FILE="/var/log/network_monitor.log"
CHECK_INTERVAL=60
TARGETS=("8.8.8.8" "1.1.1.1" "google.com" "localhost")
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}
check_ping() {
local target=$1
if ping -c 1 -W 2 "$target" &> /dev/null; then
echo "✓ $target: Reachable"
return 0
else
echo "✗ $target: Unreachable"
return 1
fi
}
check_port() {
local host=$1
local port=$2
timeout 2 bash -c "</dev/tcp/$host/$port" &>/dev/null
if [ $? -eq 0 ]; then
echo "✓ $host:$port: Open"
return 0
else
echo "✗ $host:$port: Closed"
return 1
fi
}
check_dns() {
if nslookup google.com &> /dev/null; then
echo "✓ DNS: Working"
return 0
else
echo "✗ DNS: Failed"
return 1
fi
}
monitor_network() {
echo "=== Network Status Check ==="
# Check connectivity
for target in "${TARGETS[@]}"; do
check_ping "$target"
done
# Check common ports
check_port "localhost" 22
check_port "localhost" 80
check_port "localhost" 443
# Check DNS
check_dns
# Check bandwidth (requires iftop or similar)
echo "=== Current Connections ==="
netstat -tun | grep ESTABLISHED | head -5
echo "=== Interface Statistics ==="
ip -s link show | grep -A 3 "state UP"
}
# Main monitoring loop
while true; do
echo "Starting network check..."
monitor_network | tee -a "$LOG_FILE"
echo "Waiting $CHECK_INTERVAL seconds..."
echo ""
sleep $CHECK_INTERVAL
done
🔧 Server Architecture & Operations
Server Types and Functions
Web Server
- Examples: Nginx, Apache, Caddy
- Function: Serves HTTP/HTTPS content
- Ports: 80 (HTTP), 443 (HTTPS)
- Config: Virtual hosts, SSL certificates
Database Server
- Examples: MySQL, PostgreSQL, MongoDB
- Function: Data storage and retrieval
- Ports: 3306 (MySQL), 5432 (PostgreSQL)
- Config: User permissions, replication
Application Server
- Examples: Node.js, Tomcat, Django
- Function: Runs business logic
- Ports: 3000 (Node), 8080 (Tomcat)
- Config: Environment variables, scaling
File Server
- Examples: Samba, NFS, SFTP
- Function: File sharing and storage
- Ports: 445 (SMB), 2049 (NFS)
- Config: Share permissions, quotas
How a Server Works: Complete Flow
HTTP Request Processing
- Client Request: User types URL → Browser creates HTTP request
- DNS Resolution: Browser queries DNS for IP address
- TCP Handshake: SYN → SYN-ACK → ACK (3-way handshake)
- Request Transmission: HTTP request sent over established connection
- Server Processing:
- Web server (Nginx/Apache) receives request
- Checks virtual host configuration
- Routes to appropriate application handler
- Application processes request (database queries, business logic)
- Generates HTTP response
- Response: Server sends HTTP response with status code, headers, body
- Connection Closure: FIN → FIN-ACK → ACK (graceful termination)
Example: Nginx Configuration
# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
http {
# Basic settings
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off;
# MIME types
include /etc/nginx/mime.types;
default_type application/octet-stream;
# SSL Settings
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# Logging
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript;
# Virtual Host Configuration
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location /api {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
# HTTPS Configuration
server {
listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Rest of configuration same as HTTP server
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
}
🔀 Port Forwarding & NAT
Understanding NAT (Network Address Translation)
NAT Types
- Static NAT: One-to-one mapping (public IP ↔ private IP)
- Dynamic NAT: Pool of public addresses mapped dynamically
- PAT (Port Address Translation): Multiple private IPs share one public IP using ports
- Full Cone NAT: Any external host can send to mapped port
- Restricted Cone NAT: Only specific external hosts can send
- Port Restricted Cone: Both host and port must match
- Symmetric NAT: Different mapping for each external destination
Port Forwarding Configuration Examples
Router Configuration (Generic)
# Typical home router port forwarding setup
# Access router at 192.168.1.1 → Advanced → Port Forwarding
Service Name: Web Server
External Port: 80
Internal Port: 80
Protocol: TCP
Internal IP: 192.168.1.100
Enabled: ✓
Service Name: SSH Server
External Port: 2222
Internal Port: 22
Protocol: TCP
Internal IP: 192.168.1.101
Enabled: ✓
Service Name: Minecraft Server
External Port: 25565
Internal Port: 25565
Protocol: TCP/UDP
Internal IP: 192.168.1.102
Enabled: ✓
Service Name: Security Cameras
External Port Range: 8000-8010
Internal Port Range: 8000-8010
Protocol: TCP
Internal IP: 192.168.1.150
Enabled: ✓
Linux iptables Port Forwarding
#!/bin/bash
# Linux server acting as router with iptables
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush existing rules
iptables -F
iptables -t nat -F
iptables -X
# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow loopback
iptables -A INPUT -i lo -j ACCEPT
# Port forwarding rules
# Forward external port 80 to internal web server
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80
iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 80 -j ACCEPT
# Forward external port 2222 to internal SSH
iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 192.168.1.101:22
iptables -A FORWARD -p tcp -d 192.168.1.101 --dport 22 -j ACCEPT
# Masquerade outgoing traffic
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# Save rules
iptables-save > /etc/iptables/rules.v4
# For IPv6 (if needed)
ip6tables-save > /etc/iptables/rules.v6
Windows Firewall Port Forwarding
# PowerShell as Administrator
# Enable port forwarding
netsh interface portproxy add v4tov4 listenport=80 listenaddress=0.0.0.0 connectport=80 connectaddress=192.168.1.100
netsh interface portproxy add v4tov4 listenport=443 listenaddress=0.0.0.0 connectport=443 connectaddress=192.168.1.100
netsh interface portproxy add v4tov4 listenport=3389 listenaddress=0.0.0.0 connectport=3389 connectaddress=192.168.1.150
# Show current port forwarding rules
netsh interface portproxy show all
# Windows Firewall rules to allow forwarded ports
New-NetFirewallRule -DisplayName "Allow Port 80" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
New-NetFirewallRule -DisplayName "Allow Port 443" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow
New-NetFirewallRule -DisplayName "Allow Port 3389" -Direction Inbound -Protocol TCP -LocalPort 3389 -Action Allow
# For RDP forwarding specifically
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -name "fDenyTSConnections" -Value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
Port Forwarding Security Considerations
⚠️ Security Risks
- Exposed Services: Every forwarded port is a potential attack vector
- Brute Force Attacks: SSH, RDP, and web interfaces are common targets
- Vulnerability Exploitation: Unpatched services can be compromised
- DoS Attacks: Services can be overwhelmed with traffic
- Information Disclosure: Banner grabbing reveals software versions
🔒 Security Best Practices
- Change Default Ports: Use non-standard ports for common services
- Implement Rate Limiting: Use fail2ban or similar tools
- Use VPN Instead: Access services through VPN rather than direct exposure
- Regular Updates: Keep all exposed software patched
- Strong Authentication: Use key-based auth for SSH, strong passwords elsewhere
- Firewall Rules: Restrict source IPs when possible
- Monitoring: Log and monitor all forwarded port access
- Reverse Proxy: Use Nginx as reverse proxy with WAF capabilities
📶 Wireless Networking
Wi-Fi Standards and Specifications
| Standard | Year | Frequency | Max Speed | Range | Features |
|---|---|---|---|---|---|
| 802.11b | 1999 | 2.4 GHz | 11 Mbps | 35m indoor | First widespread adoption |
| 802.11a | 1999 | 5 GHz | 54 Mbps | 25m indoor | Less interference, shorter range |
| 802.11g | 2003 | 2.4 GHz | 54 Mbps | 38m indoor | Backward compatible with 802.11b |
| 802.11n (Wi-Fi 4) | 2009 | 2.4/5 GHz | 600 Mbps | 70m indoor | MIMO, channel bonding |
| 802.11ac (Wi-Fi 5) | 2013 | 5 GHz | 3.5 Gbps | 35m indoor | MU-MIMO, wider channels |
| 802.11ax (Wi-Fi 6) | 2019 | 2.4/5/6 GHz | 9.6 Gbps | 30m indoor | OFDMA, TWT, better efficiency |
Wi-Fi Channel Planning
2.4 GHz Band Channels
- Non-overlapping channels: 1, 6, 11 (US), 1, 5, 9, 13 (Europe)
- Channel Width: 20 MHz standard, 40 MHz possible but causes interference
- Best Practice: Use channels 1, 6, or 11 only to avoid overlap
5 GHz Band Channels
- Available Channels: 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 149, 153, 157, 161, 165
- DFS Channels: 52-64, 100-140 (require radar avoidance)
- Channel Width: 20, 40, 80, or 160 MHz possible
- Best Practice: Use 80 MHz on non-DFS channels for best performance
Wi-Fi Site Survey Tools
# Linux wireless tools
sudo apt install wireless-tools iw iwlist wavemon
# Scan for networks
sudo iwlist wlan0 scan
# Check current connection
iwconfig wlan0
# Monitor mode for packet analysis
sudo airmon-ng start wlan0
sudo airodump-ng wlan0mon
# Windows tools
# netsh wlan show networks mode=bssid
# NirSoft WirelessNetView
# macOS tools
# /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s
# Professional tools
# Ekahau Site Survey
# NetSpot
# Acrylic Wi-Fi
Wireless Security Protocols
WEP
Status: Broken, never use
Crack Time: Minutes
Flaws: Weak IV, RC4 stream cipher
WPA
Status: Deprecated
Crack Time: Hours with good wordlist
Flaws: TKIP vulnerabilities
WPA2
Status: Current standard
Crack Time: Days with KRACK attack
Security: AES-CCMP, strong when using WPA2-Enterprise
WPA3
Status: Latest standard
Security: SAE, 192-bit encryption
Features: Forward secrecy, brute force protection
🔐 Network Security
Firewall Configuration Examples
UFW (Uncomplicated Firewall) - Ubuntu
# Basic UFW setup
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH
sudo ufw allow 22/tcp
sudo ufw limit 22/tcp # Rate limiting
# Allow web traffic
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Allow specific IP ranges
sudo ufw allow from 192.168.1.0/24
sudo ufw allow from 10.0.0.0/8 to any port 22
# Allow Docker
sudo ufw allow 2376/tcp # Docker daemon
sudo ufw allow 7946/tcp # Docker swarm
sudo ufw allow 7946/udp
sudo ufw allow 4789/udp # VXLAN
# Application profiles
sudo ufw app list
sudo ufw allow 'Nginx Full'
sudo ufw allow 'Apache Secure'
sudo ufw allow 'OpenSSH'
# Enable logging
sudo ufw logging on
# View status
sudo ufw status verbose
sudo ufw status numbered
# Delete rule by number
sudo ufw delete 2
# Disable/Enable
sudo ufw disable
sudo ufw enable
firewalld - CentOS/RHEL/Fedora
# Basic firewalld commands
sudo systemctl start firewalld
sudo systemctl enable firewalld
# Zones
sudo firewall-cmd --get-default-zone
sudo firewall-cmd --get-active-zones
sudo firewall-cmd --set-default-zone=public
# List services
sudo firewall-cmd --list-services
sudo firewall-cmd --list-all
# Add services
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=cockpit
# Add ports
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --permanent --add-port=9000-9010/tcp
# Rich rules (advanced)
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port port="22" protocol="tcp" accept'
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.5" reject'
# Port forwarding
sudo firewall-cmd --permanent --add-forward-port=port=80:proto=tcp:toport=8080
sudo firewall-cmd --permanent --add-forward-port=port=80:proto=tcp:toaddr=192.168.1.100
# Masquerading
sudo firewall-cmd --permanent --add-masquerade
# Reload
sudo firewall-cmd --reload
# Check
sudo firewall-cmd --list-all --zone=public
VPN Technologies
OpenVPN
- Type: SSL/TLS based
- Ports: 1194 UDP (default), 443 TCP
- Strengths: Mature, cross-platform, very configurable
- Weaknesses: Slower than WireGuard, complex setup
WireGuard
- Type: Modern UDP-based
- Ports: 51820 UDP (default)
- Strengths: Fast, simple, modern cryptography
- Weaknesses: Newer, fewer GUI tools
IPsec
- Type: Network layer
- Ports: 500 UDP, 4500 UDP
- Strengths: Enterprise standard, hardware acceleration
- Weaknesses: Complex, NAT traversal issues
Tailscale
- Type: WireGuard-based mesh
- Ports: Various
- Strengths: Zero-config, easy setup, built-in coordination server
- Weaknesses: Proprietary control plane
🔍 Network Troubleshooting
Complete Troubleshooting Methodology
Step-by-Step Troubleshooting Process
Step 1: Define the Problem
- What exactly is not working?
- When did it stop working?
- What changed recently?
- Who is affected? (Single user, department, entire organization)
- Is there an error message?
Step 2: Gather Information
- Check network diagrams and documentation
- Interview affected users
- Review monitoring systems and logs
- Note any recent changes or incidents
Step 3: Isolate the Problem
- Can you reproduce the issue?
- Is it location-specific or system-specific?
- Does it affect all applications or just one?
- Is it intermittent or constant?
Step 4: Systematic Testing
# OSI Layer Troubleshooting
1. Physical Layer (Layer 1)
- Check cable connections
- Verify link lights on NIC/router
- Test with different cable
- Check power to devices
2. Data Link Layer (Layer 2)
- Check MAC address table
- Verify VLAN configuration
- Check for spanning tree issues
- Test ARP resolution
3. Network Layer (Layer 3)
- Verify IP configuration (ipconfig/ifconfig)
- Check routing tables
- Test with ping to gateway
- Verify subnet masks
4. Transport Layer (Layer 4)
- Test with telnet/nc to specific ports
- Check firewall rules
- Verify TCP handshake
- Check for MTU issues
5. Application Layer (Layers 5-7)
- Verify DNS resolution
- Check application logs
- Test with different client
- Verify authentication
Common Network Issues and Solutions
Issue: "No Internet Connection"
- Check physical connection - Cable plugged in? Wi-Fi connected?
- Test local connectivity - Can you ping the router?
ping 192.168.1.1orping 10.0.0.1 - Check IP configuration
Windows:ipconfig /all
Linux:ip addr showorifconfig - Test DNS resolution
nslookup google.com
dig google.com - Test gateway connectivity
traceroute 8.8.8.8 - Check firewall rules
sudo ufw statusornetsh advfirewall show allprofiles - Test with different device - Is it just this computer?
- Restart network services
Windows:ipconfig /release && ipconfig /renew
Linux:sudo systemctl restart NetworkManager - Check router/modem - Restart if necessary
- Contact ISP - Last resort, check for outages
Issue: "Slow Network Speeds"
- Test baseline speed
speedtest-cliorcurl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python - - Check for bandwidth hogs
Linux:nethogsoriftop
Windows: Resource Monitor → Network tab - Test at different times - Peak vs off-peak hours
- Check for duplex mismatches
ethtool eth0(Linux)
Get-NetAdapterAdvancedProperty -Name "*"(PowerShell) - Test with wired connection - Isolate Wi-Fi issues
- Check for interference (Wi-Fi)
Use Wi-Fi analyzer tools - Test different servers
ping -c 10 google.com
mtr 8.8.8.8 - Check QoS settings - Is traffic being throttled?
- Update network drivers
- Test with different cables/ports
Issue: "Intermittent Connectivity"
- Monitor connection over time
ping -t 8.8.8.8(Windows)
ping 8.8.8.8(Linux/macOS, use Ctrl+C to stop) - Check for packet loss
ping -c 100 8.8.8.8 - Test during different activities - Streaming vs browsing
- Check event logs
Windows: Event Viewer → System logs
Linux:journalctl -f - Test with continuous trace
mtr --report 8.8.8.8 - Check for IP conflicts
arp -a
Look for duplicate IP addresses - Test DHCP lease times - Are they too short?
- Check for thermal issues - Overheating equipment
- Test power supply - Brownouts can cause resets
- Replace suspect hardware - Cables, NIC, switch ports
Advanced Troubleshooting Commands
Linux Network Diagnostics
# Comprehensive network check script
#!/bin/bash
echo "=== Network Diagnostics ==="
echo "Timestamp: $(date)"
echo ""
# 1. Interface Information
echo "1. Network Interfaces:"
ip -c addr show
echo ""
# 2. Routing Table
echo "2. Routing Table:"
ip -c route show
echo ""
# 3. DNS Configuration
echo "3. DNS Configuration:"
cat /etc/resolv.conf
echo "Nameservers:"
systemd-resolve --status | grep "DNS Servers" -A 5
echo ""
# 4. Connectivity Tests
echo "4. Connectivity Tests:"
echo "Testing gateway..."
ping -c 3 $(ip route | grep default | awk '{print $3}') 2>&1
echo ""
echo "Testing external connectivity..."
ping -c 3 8.8.8.8 2>&1
echo ""
# 5. DNS Resolution
echo "5. DNS Resolution:"
echo "Testing DNS..."
dig google.com +short 2>&1
nslookup google.com 2>&1
echo ""
# 6. Listening Ports
echo "6. Listening Ports:"
ss -tulpn | head -20
echo ""
# 7. Current Connections
echo "7. Current Connections:"
ss -tn | head -20
echo ""
# 8. Firewall Status
echo "8. Firewall Status:"
if command -v ufw &> /dev/null; then
sudo ufw status verbose
elif command -v firewall-cmd &> /dev/null; then
sudo firewall-cmd --list-all
fi
echo ""
# 9. Network Statistics
echo "9. Network Statistics:"
ip -s link show
echo ""
# 10. MTU Check
echo "10. MTU Check:"
ip link | grep mtu
echo ""
echo "=== Diagnostics Complete ==="
Windows Network Diagnostics
# Windows PowerShell Network Diagnostics
# Save as network-diag.ps1
Write-Host "=== Windows Network Diagnostics ===" -ForegroundColor Green
Write-Host "Timestamp: $(Get-Date)`n" -ForegroundColor Yellow
# 1. Network Adapters
Write-Host "1. Network Adapters:" -ForegroundColor Cyan
Get-NetAdapter | Format-Table Name, InterfaceDescription, Status, LinkSpeed -AutoSize
Write-Host ""
# 2. IP Configuration
Write-Host "2. IP Configuration:" -ForegroundColor Cyan
Get-NetIPConfiguration | Format-List
Write-Host ""
# 3. DNS Client Cache
Write-Host "3. DNS Cache:" -ForegroundColor Cyan
Get-DnsClientCache | Select-Object -First 10 Entry,RecordName,RecordType,Data | Format-Table -AutoSize
Write-Host ""
# 4. Routing Table
Write-Host "4. Routing Table:" -ForegroundColor Cyan
Get-NetRoute | Select-Object -First 20 DestinationPrefix,NextHop,RouteMetric,InterfaceAlias | Format-Table -AutoSize
Write-Host ""
# 5. ARP Cache
Write-Host "5. ARP Cache:" -ForegroundColor Cyan
Get-NetNeighbor | Select-Object -First 15 IPAddress,LinkLayerAddress,State,InterfaceAlias | Format-Table -AutoSize
Write-Host ""
# 6. Firewall Rules
Write-Host "6. Active Firewall Rules:" -ForegroundColor Cyan
Get-NetFirewallRule -Enabled True | Select-Object -First 10 DisplayName,Profile,Direction,Action | Format-Table -AutoSize
Write-Host ""
# 7. Network Connections
Write-Host "7. Active TCP Connections:" -ForegroundColor Cyan
Get-NetTCPConnection -State Established | Select-Object -First 10 LocalAddress,LocalPort,RemoteAddress,RemotePort,State | Format-Table -AutoSize
Write-Host ""
# 8. Connectivity Tests
Write-Host "8. Connectivity Tests:" -ForegroundColor Cyan
$gateway = (Get-NetRoute -DestinationPrefix "0.0.0.0/0").NextHop
Write-Host "Testing gateway ($gateway)..." -ForegroundColor Yellow
Test-Connection -ComputerName $gateway -Count 3 -Quiet
Write-Host "Testing external (8.8.8.8)..." -ForegroundColor Yellow
Test-Connection -ComputerName "8.8.8.8" -Count 3 -Quiet
Write-Host "Testing DNS (google.com)..." -ForegroundColor Yellow
Test-Connection -ComputerName "google.com" -Count 3 -Quiet
Write-Host ""
# 9. DNS Resolution
Write-Host "9. DNS Resolution Tests:" -ForegroundColor Cyan
Resolve-DnsName -Name "google.com" -Type A | Select-Object -First 3
Write-Host ""
# 10. Network Adapter Statistics
Write-Host "10. Adapter Statistics:" -ForegroundColor Cyan
Get-NetAdapterStatistics | Select-Object Name,ReceivedBytes,SentBytes,ReceivedUnicastPackets,SentUnicastPackets | Format-Table -AutoSize
Write-Host ""
Write-Host "=== Diagnostics Complete ===" -ForegroundColor Green
# Additional troubleshooting commands
Write-Host "`nQuick Fix Commands:" -ForegroundColor Magenta
Write-Host "Release/Renew IP: ipconfig /release && ipconfig /renew"
Write-Host "Flush DNS: ipconfig /flushdns"
Write-Host "Reset Winsock: netsh winsock reset"
Write-Host "Reset TCP/IP: netsh int ip reset"
Write-Host "Restart Network Adapter: Restart-NetAdapter -Name '*'"
📈 Network Monitoring Tools
Open Source Monitoring Solutions
Zabbix
- Type: Enterprise monitoring
- Best For: Large networks, custom monitoring
- Features: Auto-discovery, alerting, graphing
- Complexity: High
Prometheus + Grafana
- Type: Time-series monitoring
- Best For: Cloud-native, containers
- Features: Pull-based, powerful query language
- Complexity: Medium-High
Nagios
- Type: Classic monitoring
- Best For: Service monitoring
- Features: Plugin architecture, mature
- Complexity: High
LibreNMS
- Type: Network monitoring
- Best For: Network device monitoring
- Features: Auto-discovery, Oxidized integration
- Complexity: Medium
Command Line Monitoring Tools
# Real-time monitoring commands
# Network traffic
sudo iftop -i eth0 # Bandwidth usage per connection
sudo nethogs # Bandwidth per process
sudo bmon # Multiple interface monitor
sudo iptraf-ng # Advanced traffic analysis
# Connection monitoring
sudo netstat -tunap # All connections with processes
sudo ss -tunap # Faster netstat replacement
sudo lsof -i # Open files (sockets)
sudo tcpdump -i eth0 -n # Packet capture
# Bandwidth testing
iperf3 -s # Server mode
iperf3 -c server_ip # Client mode
speedtest-cli # Internet speed test
mtr --report google.com # Continuous traceroute
# SNMP monitoring
snmpwalk -v 2c -c public router_ip system
snmpget -v 2c -c public router_ip ifInOctets.1
# Web server monitoring
ab -n 1000 -c 10 http://example.com/ # Apache benchmark
siege -c 10 -t 1M http://example.com # Load testing
# DNS monitoring
dig +trace example.com # Full DNS trace
dnstop -l 5 eth0 # DNS traffic monitor
# SSL monitoring
openssl s_client -connect example.com:443 -servername example.com
sslscan example.com:443
# Port scanning
nmap -sS -sV -O target_ip # Stealth scan with version detection
masscan -p1-65535 target_ip --rate=1000
📚 Protocols Deep Dive
TCP vs UDP Comparison
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Guaranteed delivery | Best-effort delivery |
| Ordering | In-order delivery | No ordering guarantee |
| Error Checking | Checksum, retransmission | Checksum only |
| Flow Control | Sliding window | None |
| Congestion Control | Multiple algorithms | None |
| Overhead | High (20-60 bytes) | Low (8 bytes) |
| Speed | Slower | Faster |
| Use Cases | Web, email, file transfer | DNS, VoIP, gaming, streaming |
| Header Size | 20-60 bytes | 8 bytes |
Common Ports Reference
Web & Email
- 20/21: FTP (Data/Control)
- 22: SSH/SFTP
- 25: SMTP
- 53: DNS
- 80: HTTP
- 110: POP3
- 143: IMAP
- 443: HTTPS
- 465: SMTPS
- 587: SMTP Submission
- 993: IMAPS
- 995: POP3S
Remote Access
- 22: SSH
- 23: Telnet
- 3389: RDP
- 5900: VNC
- 5985: WinRM HTTP
- 5986: WinRM HTTPS
Database
- 1433: MS SQL Server
- 1521: Oracle
- 3306: MySQL/MariaDB
- 5432: PostgreSQL
- 27017: MongoDB
- 6379: Redis
Gaming & Media
- 25565: Minecraft
- 27015: Steam/CS:GO
- 3074: Xbox Live
- 3478: STUN
- 5060: SIP
- 1935: RTMP
- 554: RTSP
⚠️ Security Best Practices
• Always use HTTPS instead of HTTP
• Disable unused services and ports
• Regularly update all network equipment firmware
• Implement network segmentation (VLANs)
• Use strong, unique passwords for all devices
• Enable logging and monitor logs regularly
• Implement intrusion detection/prevention systems
• Regularly backup network device configurations
• Use VPNs for remote access instead of port forwarding
• Conduct regular security audits and penetration tests