%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#E67E22', 'secondaryColor': '#16A085', 'tertiaryColor': '#7F8C8D', 'fontSize': '11px'}}}%%
flowchart TD
Start["Device won't connect"]
L1["Layer 1: Physical"]
L1Q{"Signal<br/>detected?"}
L1Fix["Check: Power, antenna,<br/>distance, obstacles"]
L2["Layer 2: Data Link"]
L2Q{"Correct<br/>credentials?"}
L2Fix["Check: SSID, password,<br/>MAC filter, channel"]
L3["Layer 3: Network"]
L3Q{"Got IP<br/>address?"}
L3Fix["Check: DHCP, static IP,<br/>subnet, gateway"]
L4["Layer 4: Transport"]
L4Q{"Can ping<br/>gateway?"}
L4Fix["Check: Routing,<br/>firewall, NAT"]
L7["Layer 7: Application"]
L7Q{"DNS<br/>working?"}
L7Fix["Check: DNS server,<br/>hostname resolution"]
Success["Connection<br/>established!"]
Start --> L1
L1 --> L1Q
L1Q -->|No| L1Fix
L1Fix --> L1Q
L1Q -->|Yes| L2
L2 --> L2Q
L2Q -->|No| L2Fix
L2Fix --> L2Q
L2Q -->|Yes| L3
L3 --> L3Q
L3Q -->|No| L3Fix
L3Fix --> L3Q
L3Q -->|Yes| L4
L4 --> L4Q
L4Q -->|No| L4Fix
L4Fix --> L4Q
L4Q -->|Yes| L7
L7 --> L7Q
L7Q -->|No| L7Fix
L7Fix --> L7Q
L7Q -->|Yes| Success
style Start fill:#E67E22,stroke:#2C3E50,color:#fff
style Success fill:#16A085,stroke:#2C3E50,color:#fff
style L1 fill:#2C3E50,stroke:#16A085,color:#fff
style L2 fill:#2C3E50,stroke:#16A085,color:#fff
style L3 fill:#2C3E50,stroke:#16A085,color:#fff
style L4 fill:#2C3E50,stroke:#16A085,color:#fff
style L7 fill:#2C3E50,stroke:#16A085,color:#fff
623 Networking Basics: Hands-On Configuration
623.1 Learning Objectives
By the end of this chapter, you will be able to:
- Configure IoT Networks: Set up ESP32 devices with proper network configuration
- Understand Port Numbers: Identify common IoT protocol ports and their uses
- Troubleshoot Networks: Apply systematic layer-by-layer troubleshooting
- Implement Security: Apply basic network security practices for IoT
- Optimize Performance: Understand bandwidth and latency considerations
623.2 Prerequisites
Before diving into this chapter, you should be familiar with:
- Networking Basics: Introduction: Core networking concepts including layers, IP addressing, and network types
- Networking Basics: Protocols and MAC: Understanding protocol layers and MAC classification
623.3 Hands-On: Network Configuration
623.3.1 ESP32 Network Configuration Example
#include <WiFi.h>
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin("MyNetwork", "MyPassword");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Display network information
Serial.println("\n=== Network Configuration ===");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
Serial.print("Subnet Mask: ");
Serial.println(WiFi.subnetMask());
Serial.print("Gateway: ");
Serial.println(WiFi.gatewayIP());
Serial.print("DNS: ");
Serial.println(WiFi.dnsIP());
Serial.print("MAC Address: ");
Serial.println(WiFi.macAddress());
Serial.print("Signal Strength (RSSI): ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
}
void loop() {
// Your IoT application code here
}Key Configuration Parameters:
| Parameter | Purpose | Example |
|---|---|---|
| IP Address | Deviceโs unique network identity | 192.168.1.100 |
| Subnet Mask | Defines local network size | 255.255.255.0 (/24 = 254 hosts) |
| Gateway | Router to reach other networks | 192.168.1.1 |
| DNS | Converts names to IP addresses | 8.8.8.8 (Google DNS) |
| MAC Address | Hardware identifier | DC:A6:32:AB:CD:EF |
623.3.2 Python Network Scanner
#!/usr/bin/env python3
"""Simple network scanner for IoT devices."""
import socket
import concurrent.futures
from typing import List, Tuple
def scan_host(ip: str, port: int) -> Tuple[str, int, bool]:
"""Check if a host has a port open."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ip, port))
sock.close()
return (ip, port, result == 0)
except socket.error:
return (ip, port, False)
def scan_network(base_ip: str, ports: List[int]) -> List[dict]:
"""Scan network for devices with open ports."""
devices = []
tasks = []
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Generate all IP/port combinations
for i in range(1, 255):
ip = f"{base_ip}.{i}"
for port in ports:
tasks.append(executor.submit(scan_host, ip, port))
# Collect results
for future in concurrent.futures.as_completed(tasks):
ip, port, is_open = future.result()
if is_open:
devices.append({"ip": ip, "port": port})
return devices
if __name__ == "__main__":
# Common IoT ports
iot_ports = [80, 443, 1883, 8883, 5683, 22]
print("Scanning local network for IoT devices...")
found = scan_network("192.168.1", iot_ports)
for device in found:
print(f"Found: {device['ip']}:{device['port']}")623.4 Port Numbers
Port numbers identify specific applications or services on a device. They range from 0 to 65535.
623.4.1 Common IoT Protocol Ports
| Port | Protocol | Description | Security |
|---|---|---|---|
| 80 | HTTP | Web servers, REST APIs | Unencrypted |
| 443 | HTTPS | Secure web, TLS | Encrypted |
| 1883 | MQTT | IoT messaging | Unencrypted |
| 8883 | MQTTS | MQTT over TLS | Encrypted |
| 5683 | CoAP | Constrained devices | Unencrypted |
| 5684 | CoAPS | CoAP over DTLS | Encrypted |
| 22 | SSH | Secure shell access | Encrypted |
| 23 | Telnet | Remote access | Unencrypted (avoid!) |
| 502 | Modbus TCP | Industrial protocols | Unencrypted |
| 5353 | mDNS | Local device discovery | N/A |
| 123 | NTP | Time synchronization | N/A |
| 53 | DNS | Domain name resolution | Usually unencrypted |
Always use encrypted ports in production:
- Use 8883 instead of 1883 for MQTT
- Use 5684 instead of 5683 for CoAP
- Use 443 instead of 80 for HTTP
- Never use Telnet (port 23) - use SSH (port 22) instead
Unencrypted ports are acceptable only for development and testing on isolated networks.
623.4.2 Port Number Ranges
| Range | Type | Examples |
|---|---|---|
| 0-1023 | Well-known ports | HTTP (80), HTTPS (443), SSH (22) |
| 1024-49151 | Registered ports | MQTT (1883), CoAP (5683) |
| 49152-65535 | Dynamic/private | Client-side connections |
623.5 Network Troubleshooting
623.5.1 Layer-by-Layer Troubleshooting Approach
When an IoT device wonโt connect, work systematically from Physical layer up:
623.5.2 Troubleshooting Checklist by Layer
Layer 1 (Physical):
- Is the device powered on?
- Is RSSI > -70 dBm? (Check signal strength)
- Is the antenna connected properly?
- Any physical obstacles (metal, concrete)?
- Is the device within range?
Layer 2 (Data Link):
- Correct SSID? (case-sensitive)
- Correct password? (case-sensitive)
- MAC address whitelisted? (if MAC filtering enabled)
- Correct Wi-Fi channel? (2.4 GHz vs 5 GHz - ESP32 only supports 2.4 GHz)
- Channel congestion?
Layer 3 (Network):
- Did device get IP address? (check DHCP lease)
- IP address conflict? (two devices with same IP)
- Correct subnet mask?
- Correct gateway configured?
Layer 4 (Transport) / Layer 7 (Application):
- Can ping the gateway? (
ping 192.168.1.1) - Can ping external IP? (
ping 8.8.8.8) - DNS resolution working? (
nslookup google.com) - Firewall blocking ports?
- Correct protocol port configured?
623.5.3 ESP32 Diagnostic Commands
// Check Wi-Fi status
Serial.println(WiFi.status()); // WL_CONNECTED = 3
// Check signal strength
int rssi = WiFi.RSSI();
Serial.print("Signal: ");
Serial.print(rssi);
Serial.println(" dBm");
// Check IP configuration
Serial.print("IP: ");
Serial.println(WiFi.localIP());
Serial.print("Gateway: ");
Serial.println(WiFi.gatewayIP());
// Check connectivity (simple ping equivalent)
WiFiClient client;
if (client.connect("8.8.8.8", 53)) {
Serial.println("Internet: OK");
client.stop();
} else {
Serial.println("Internet: FAIL");
}623.5.4 Common Issues and Solutions
| Problem | Symptoms | Solution |
|---|---|---|
| Weak signal | RSSI < -80 dBm, frequent disconnects | Move closer, add antenna, use extender |
| Wrong credentials | Connection timeout, auth failure | Verify SSID/password case |
| No IP address | IP shows 0.0.0.0 or 169.254.x.x | Check DHCP server, try static IP |
| Canโt reach gateway | Ping gateway fails | Check subnet mask, gateway IP |
| Canโt reach internet | Ping 8.8.8.8 fails | Check ISP, router, NAT |
| DNS not working | Names fail, IPs work | Check DNS server configuration |
| Port blocked | Connection refused | Check firewall rules |
623.6 Security Basics
IoT devices are prime targets for attacks due to:
- Often deployed in physical locations with no supervision
- Many use default credentials
- Limited resources for security features
- Long deployment lifetimes with infrequent updates
623.6.1 Essential Security Practices
1. Change Default Credentials
// BAD: Default credentials
const char* mqtt_user = "admin";
const char* mqtt_pass = "admin";
// GOOD: Unique credentials per device
const char* mqtt_user = "sensor_temp_001";
const char* mqtt_pass = "Xk9#mP2@vL5!nQ8$";2. Use TLS Encryption
// BAD: Unencrypted MQTT
client.connect("broker.example.com", 1883);
// GOOD: TLS-encrypted MQTT
WiFiClientSecure secureClient;
secureClient.setCACert(root_ca);
client.setClient(secureClient);
client.connect("broker.example.com", 8883);3. Network Segmentation
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#E67E22', 'secondaryColor': '#16A085', 'tertiaryColor': '#7F8C8D', 'fontSize': '12px'}}}%%
graph TB
subgraph Internet
Cloud["Cloud Services"]
end
subgraph DMZ["DMZ (Firewall Protected)"]
Gateway["IoT Gateway"]
end
subgraph IoT["IoT VLAN (Isolated)"]
S1["Sensor 1"]
S2["Sensor 2"]
S3["Sensor 3"]
end
subgraph Corp["Corporate VLAN"]
PC["Workstations"]
Server["Internal Servers"]
end
Cloud <--> Gateway
Gateway <--> S1
Gateway <--> S2
Gateway <--> S3
Gateway -.->|"Restricted Access"| PC
style Cloud fill:#E67E22,stroke:#2C3E50,color:#fff
style Gateway fill:#16A085,stroke:#2C3E50,color:#fff
style S1 fill:#2C3E50,stroke:#16A085,color:#fff
style S2 fill:#2C3E50,stroke:#16A085,color:#fff
style S3 fill:#2C3E50,stroke:#16A085,color:#fff
style PC fill:#7F8C8D,stroke:#2C3E50,color:#fff
style Server fill:#7F8C8D,stroke:#2C3E50,color:#fff
4. Firmware Updates
- Implement secure OTA (Over-The-Air) updates
- Sign firmware images cryptographically
- Validate signatures before applying updates
- Have rollback mechanism for failed updates
5. Minimal Attack Surface
- Disable unused services and ports
- Remove debugging interfaces in production
- Use principle of least privilege
- Log security events for monitoring
623.6.2 Security Checklist
623.7 Bandwidth and Latency Considerations
623.7.1 IoT vs Traditional IT: Key Differences
| Aspect | Traditional IT | IoT |
|---|---|---|
| Data Size | MB to GB | Bytes to KB |
| Traffic Pattern | Continuous | Bursty, periodic |
| Latency Tolerance | Seconds OK | ms to seconds |
| Bandwidth Priority | High throughput | Low power |
| Reliability | High availability | Graceful degradation |
623.7.2 Typical IoT Data Sizes
| Data Type | Size | Frequency | Daily Data |
|---|---|---|---|
| Temperature reading | 4 bytes | Every 5 min | 1.2 KB |
| GPS coordinates | 16 bytes | Every 30 sec | 46 KB |
| Accelerometer sample | 12 bytes | 100 Hz | 4.3 MB |
| Image capture | 50 KB | Every hour | 1.2 MB |
| Audio clip (10s) | 160 KB | On event | Variable |
623.7.3 Protocol Overhead Comparison
| Protocol | Header Size | Typical Payload | Overhead Ratio |
|---|---|---|---|
| HTTP | ~300 bytes | 10 bytes | 30:1 |
| MQTT | 2-5 bytes | 10 bytes | 0.5:1 |
| CoAP | 4 bytes | 10 bytes | 0.4:1 |
| UDP raw | 8 bytes | 10 bytes | 0.8:1 |
Reduce Overhead:
- Use MQTT or CoAP instead of HTTP for small payloads
- Use binary formats (CBOR, MessagePack) instead of JSON
- Aggregate multiple readings into single transmission
Manage Bandwidth:
- Adjust reporting frequency based on data change rate
- Use compression for larger payloads
- Implement local filtering/aggregation
Optimize Latency:
- Use UDP for non-critical real-time data
- Keep persistent connections when possible
- Colocate edge processing near devices
623.8 Best Practices Summary
623.8.1 Network Design
- Choose the right protocol for your constraints (power, range, bandwidth)
- Design for failure - networks are unreliable, buffer data locally
- Plan IP addressing - use static IPs for critical devices, document allocations
- Segment networks - isolate IoT from corporate networks
623.8.2 Implementation
- Test in realistic conditions - not just on your desk
- Monitor signal strength - RSSI should be > -70 dBm for reliability
- Implement reconnection logic - networks will drop, handle gracefully
- Log network events - aids troubleshooting and security monitoring
623.8.3 Security
- Encrypt everything - TLS/DTLS is mandatory in production
- Authenticate everything - no anonymous connections
- Update regularly - vulnerabilities are discovered continuously
- Assume breach - design for detection and containment
623.9 Whatโs Next
Now that you understand network configuration, troubleshooting, and security, continue to:
- Networking Basics: Labs and Practice - Interactive labs, Python implementations, and comprehensive knowledge checks with detailed answers
You can also return to the Networking Basics Overview for navigation to all related chapters.