Low-Level Networking

Back

Loading concept...

🌐 Node.js: Low-Level Networking

The Secret Postal System Inside Your Computer


🏠 The Big Picture: Your Computer’s Mail Room

Imagine your computer is a giant building. Inside, there’s a mail room where letters come in and go out. But this isn’t ordinary mail—it’s super-fast digital mail that travels through wires and the air!

Node.js gives you special tools to work in this mail room. Today, we’ll learn about five magic helpers:

  1. DNS - The address book finder
  2. Net - The telephone operator
  3. TCP Server - Your own phone booth
  4. Dgram - The quick note thrower
  5. TLS - The secret code writer

Let’s meet each one!


📖 Chapter 1: DNS Module - The Address Book

What is DNS?

When you type google.com, your computer doesn’t understand words. It needs numbers! DNS is like a giant phone book that converts names to numbers.

Real Life Example:

  • You say: “Call Grandma”
  • Phone looks up: “Grandma = 555-1234”
  • Phone dials the number!

DNS does the same thing for websites!

Using the DNS Module

const dns = require('dns');

// Find the number for google.com
dns.lookup('google.com', (err, address) => {
  if (err) {
    console.log('Could not find!');
    return;
  }
  console.log('Found:', address);
  // Output: Found: 142.250.185.46
});

DNS Methods You Should Know

Method What It Does
lookup() Finds one IP address
resolve4() Finds all IPv4 addresses
resolve6() Finds all IPv6 addresses
reverse() Finds name from number

More Examples

// Get ALL addresses for a website
dns.resolve4('google.com', (err, addresses) => {
  console.log('All addresses:', addresses);
  // ['142.250.185.46', '142.250.185.78']
});

// Find name from IP (reverse lookup)
dns.reverse('8.8.8.8', (err, hostnames) => {
  console.log('Name:', hostnames);
  // ['dns.google']
});

🎯 Key Takeaway

DNS is your computer’s phone book. It turns names into numbers so computers can talk to each other!


📞 Chapter 2: Net Module - The Telephone System

What is the Net Module?

The net module lets your computer make “phone calls” to other computers. These calls use something called TCP—think of it as a reliable phone line where every word is heard clearly.

Why Use Net?

  • Build chat applications
  • Create game servers
  • Connect databases
  • Make custom protocols

Basic Net Concepts

graph TD A["Your Computer"] -->|Makes Call| B["Net Module"] B -->|Connects To| C["Other Computer"] C -->|Talks Back| B B -->|Delivers Message| A

Creating a Simple Connection

const net = require('net');

// Connect to a server
const client = net.createConnection({
  host: 'example.com',
  port: 80
}, () => {
  console.log('Connected!');
  client.write('Hello Server!');
});

// Listen for response
client.on('data', (data) => {
  console.log('Server says:', data.toString());
});

The Socket - Your Digital Phone

When you connect, you get a socket. Think of it as holding a phone:

  • write() - You talk into it
  • on('data') - You listen to it
  • end() - You hang up

🎯 Key Takeaway

The Net module is like a telephone system. It creates reliable connections where messages arrive in order, and nothing gets lost!


🏗️ Chapter 3: Creating a TCP Server

What’s a TCP Server?

A TCP server is like opening a pizza shop. You set up shop, wait for customers (clients) to call, take their orders, and send back pizzas (responses)!

graph TD A["TCP Server"] -->|Listens on Port| B["Port 3000"] C["Client 1"] -->|Connects| B D["Client 2"] -->|Connects| B E["Client 3"] -->|Connects| B B -->|Handles All| A

Building Your First TCP Server

const net = require('net');

// Create the server (open shop!)
const server = net.createServer((socket) => {
  console.log('Customer connected!');

  // Say hello to customer
  socket.write('Welcome to my server!\n');

  // Listen to what customer says
  socket.on('data', (data) => {
    console.log('Customer said:', data.toString());
    socket.write('I heard you!\n');
  });

  // Customer leaves
  socket.on('end', () => {
    console.log('Customer disconnected');
  });
});

// Start listening (open the doors!)
server.listen(3000, () => {
  console.log('Server ready on port 3000!');
});

Testing Your Server

Open a terminal and type:

telnet localhost 3000

You’ll see: Welcome to my server!

Server Events

Event When It Happens
connection New client connects
error Something goes wrong
close Server shuts down
listening Server starts

Echo Server - A Fun Example

const net = require('net');

const server = net.createServer((socket) => {
  socket.write('Echo Server! Type anything:\n');

  socket.on('data', (data) => {
    // Send back what they said!
    socket.write('You said: ' + data);
  });
});

server.listen(4000);
console.log('Echo server on port 4000!');

🎯 Key Takeaway

A TCP Server is like a shop that waits for customers. When someone connects, you can talk back and forth reliably!


📬 Chapter 4: Dgram Module - Quick Notes

What is Dgram?

Remember how TCP is like a phone call? UDP (dgram) is like throwing paper airplanes! You throw your message and hope it arrives. It’s fast, but not always reliable.

When to Use UDP?

  • Video games - Speed matters more than perfection
  • Video streaming - Missing one frame is okay
  • DNS queries - Quick lookups
  • Broadcasting - Sending to many at once

UDP vs TCP

Feature TCP (Net) UDP (Dgram)
Reliable ✅ Yes ❌ No
Ordered ✅ Yes ❌ No
Fast 🐢 Slower 🚀 Faster
Connection Required Not needed
graph LR A["TCP"] -->|Like| B["Phone Call"] C["UDP"] -->|Like| D["Paper Airplane"]

Creating a UDP Server

const dgram = require('dgram');

// Create UDP socket
const server = dgram.createSocket('udp4');

// When message arrives
server.on('message', (msg, rinfo) => {
  console.log(`Got: ${msg}`);
  console.log(`From: ${rinfo.address}:${rinfo.port}`);
});

// Start listening
server.bind(5000, () => {
  console.log('UDP server on port 5000!');
});

Sending a UDP Message

const dgram = require('dgram');
const client = dgram.createSocket('udp4');

const message = Buffer.from('Hello UDP!');

client.send(message, 5000, 'localhost', (err) => {
  console.log('Message thrown!');
  client.close();
});

Broadcasting to Everyone

const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

socket.bind(() => {
  socket.setBroadcast(true);

  const message = Buffer.from('Hello everyone!');
  socket.send(message, 5000, '255.255.255.255');
});

🎯 Key Takeaway

UDP (dgram) is like throwing paper airplanes. Super fast, but messages might not arrive. Use it when speed matters more than reliability!


🔒 Chapter 5: TLS Module - Secret Codes

What is TLS?

TLS is like putting your letter in a locked box. Only the person with the key can open it! It keeps your messages safe from sneaky people trying to read them.

Why TLS Matters

Without TLS:

You → "My password is cat123" → Bad Guy sees it! → Server

With TLS:

You → "xK9#mL2@pQ" → Bad Guy confused → Server decodes it!

How TLS Works

graph TD A["Client"] -->|1. Hello!| B["Server"] B -->|2. Here's my certificate| A A -->|3. I trust you!| B B -->|4. Let's make secret keys| A A -->|5. Encrypted chat begins| B

Creating a TLS Server

First, you need certificates (like official ID cards):

const tls = require('tls');
const fs = require('fs');

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem')
};

const server = tls.createServer(options, (socket) => {
  console.log('Secure connection!');
  socket.write('Welcome to secure server!\n');

  socket.on('data', (data) => {
    console.log('Received:', data.toString());
  });
});

server.listen(8000, () => {
  console.log('TLS server on port 8000!');
});

Connecting Securely (TLS Client)

const tls = require('tls');

const options = {
  host: 'localhost',
  port: 8000,
  // For testing with self-signed certs
  rejectUnauthorized: false
};

const client = tls.connect(options, () => {
  console.log('Connected securely!');
  client.write('Secret message!');
});

client.on('data', (data) => {
  console.log('Server says:', data.toString());
});

TLS vs Regular Net

Feature Net (TCP) TLS
Encrypted ❌ No ✅ Yes
Needs Certs ❌ No ✅ Yes
HTTPS Uses ❌ No ✅ Yes
Setup Easy More steps

🎯 Key Takeaway

TLS wraps your messages in a secret code. Even if someone intercepts them, they can’t read anything! It’s like whispering in a secret language only you and your friend know.


🎓 Summary: Your Networking Toolkit

graph TD A["Node.js Networking"] --> B["DNS"] A --> C["Net"] A --> D["TCP Server"] A --> E["Dgram"] A --> F["TLS"] B -->|Finds addresses| G["📖 Phone Book"] C -->|Makes connections| H["📞 Phone Calls"] D -->|Accepts connections| I["🏪 Your Shop"] E -->|Fast messages| J["✈️ Paper Planes"] F -->|Secret messages| K["🔐 Locked Box"]

Quick Reference

Module Purpose Like…
dns Find IP addresses Phone book
net TCP connections Phone calls
server Accept connections Opening a shop
dgram UDP messages Paper airplanes
tls Secure connections Secret codes

🚀 What You Learned Today

  1. DNS helps find computer addresses (like a phone book)
  2. Net creates reliable connections (like phone calls)
  3. TCP Servers wait for clients (like opening a shop)
  4. Dgram sends fast but unreliable messages (like paper airplanes)
  5. TLS encrypts everything (like secret codes)

You now have the power to build:

  • Chat applications
  • Game servers
  • Secure websites
  • Real-time systems
  • Custom protocols

You’re now a Low-Level Networking wizard! 🧙‍♂️


Remember: Every website, every app, every online game uses these concepts. Now you understand the magic behind the scenes!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.