If you've ever needed to model a network where one central device connects to every other node, you've already run into star topology. Understanding the code behind it helps you build network simulations, test communication protocols, or set up lab environments for learning. A solid star topology code implementation example saves hours of guesswork and gives you a working foundation to modify for your own projects.

What does a star topology implementation look like in code?

At its core, a star topology has one central node often called a hub or switch and multiple peripheral nodes connected only to that center. In code, you represent this as a data structure where the central node holds references (or connections) to every other node, but peripheral nodes only connect back to the center.

Here's a straightforward Python example using dictionaries and simple classes:

class Node:
 def __init__(self, name):
 self.name = name
 self.connections = []

 def connect(self, other_node):
 self.connections.append(other_node)

 def send(self, message, destination):
 print(f"{self.name} sends to hub: '{message}' (for {destination.name})")
 # In a star topology, all messages pass through the hub
 hub.forward(self, message, destination)

 def receive(self, message, sender):
 print(f"{self.name} received from {sender.name}: '{message}'")


class Hub(Node):
 def __init__(self, name):
 super().__init__(name)

 def forward(self, sender, message, destination):
 if destination in self.connections:
 print(f"Hub routing message from {sender.name} to {destination.name}")
 destination.receive(message, sender)
 else:
 print(f"Hub: {destination.name} not found in network")


# Build the star topology
hub = Hub("Hub")
node_a = Node("Computer-A")
node_b = Node("Printer-B")
node_c = Node("Server-C")

# Connect all peripheral nodes to the hub
for node in [node_a, node_b, node_c]:
 hub.connect(node)

# Communication example
node_a.send("Print document", node_b)
node_c.send("File request", node_a)

This example keeps things simple. The hub acts as the central relay. No peripheral node talks directly to another they all go through the hub. That's the defining trait of star topology code.

How do you build this with adjacency lists or graph structures?

For larger simulations, using a graph library makes more sense. Python's networkx library handles this well:

import networkx as nx
import matplotlib.pyplot as plt

# Create the graph
star = nx.Graph()

# Define the hub
hub = "Switch"

# Define peripheral nodes
peripherals = ["PC-1", "PC-2", "PC-3", "PC-4", "Server"]

# Add edges from hub to each peripheral
for node in peripherals:
 star.add_edge(hub, node)

# Visualize
pos = nx.spring_layout(star, center=[0, 0])
nx.draw(star, pos, with_labels=True, node_size=2000,
 node_color="lightblue", font_size=10, font_weight="bold")
plt.title("Star Topology Network")
plt.show()

# Print adjacency info
print("Connections:")
for node in star.nodes():
 neighbors = list(star.neighbors(node))
 print(f" {node} → {neighbors}")

This approach gives you visual output and lets you programmatically check paths, count connections, or simulate failures. If you need to understand the symbols used in network diagrams, our guide on network topology diagram symbols and meanings covers that in detail.

Can you implement star topology in C or Java?

Yes. The logic stays the same across languages you just change the syntax. Here's a C-style pseudocode outline:

#define MAX_NODES 10

typedef struct {
 char name[50];
 int id;
} Node;

typedef struct {
 Node hub;
 Node peripherals[MAX_NODES];
 int peripheral_count;
} StarNetwork;

void send_message(StarNetwork net, int from_id, int to_id, char msg) {
 // All messages route through the hub
 printf("%s -> Hub -> %s: %s\n",
 net->peripherals[from_id].name,
 net->peripherals[to_id].name, msg);
}

In Java, you'd use a HashMap<String, List<String>> where the hub key maps to all connected nodes. The structure mirrors the Python approach just with Java's type system and syntax.

What are the most common mistakes when implementing star topology?

  • Letting peripheral nodes connect directly. In a true star topology, nodes only link to the hub. If your code allows node-to-node edges, you've built a different topology possibly a partial mesh. Check mesh network topology configuration if that's what you need instead.
  • Not handling hub failure. The biggest real-world risk of star topology is the single point of failure. Your simulation code should model what happens when the hub goes offline every node loses connectivity.
  • Hardcoding node counts. Use arrays or dynamic lists instead of fixed variable names. If you need to add a sixth node, you shouldn't have to rewrite your code.
  • Ignoring message direction. Some implementations forget that messages must pass through the hub. Write explicit routing logic rather than just storing neighbor lists.
  • Skipping validation. Always check that a destination node actually exists before routing a message. Null pointer errors are common in poorly written topology code.

When is star topology the right choice for your project?

Star topology works best when you have a central server, switch, or access point, and you want simple, predictable connections. Common use cases include:

  • Small office or home LANs where a switch connects all devices
  • Lab simulations for networking courses or certification prep (CCNA, CompTIA Network+)
  • IoT prototyping where a central gateway manages multiple sensors
  • Client-server models where all communication passes through one authoritative node

If your project needs redundant paths or decentralized communication, a different structure fits better. Understanding the differences between topologies helps you pick the right one.

How do you test and extend your star topology code?

Once your basic implementation works, try these exercises to deepen your understanding:

  1. Add failure simulation. Temporarily disable the hub and verify that no messages get through. Then re-enable it and confirm normal operation resumes.
  2. Track message latency. Add a hop counter. In star topology, every message should take exactly two hops (source → hub → destination).
  3. Scale up. Generate 50 or 100 nodes programmatically and verify your code handles the volume without errors.
  4. Compare topologies. Implement the same scenario using star, bus, and mesh structures. Note the differences in connection count, complexity, and failure behavior.
  5. Add weighted edges. Assign bandwidth or latency values to each connection and simulate realistic network conditions.

Practical checklist before you deploy or submit your code

  • ☐ Hub node is clearly defined and distinct from peripheral nodes
  • ☐ All peripheral nodes connect only to the hub
  • ☐ Message routing passes through the hub no direct node-to-node shortcuts
  • ☐ Hub failure is handled gracefully (error message, not a crash)
  • ☐ Node count is dynamic, not hardcoded
  • ☐ Destination validation prevents null pointer or key errors
  • ☐ Code includes comments explaining the topology logic
  • ☐ You've tested with at least 4–5 peripheral nodes

Next step: Take the Python example above, run it locally, then modify it to simulate a hub failure. That single exercise will show you both the simplicity and the vulnerability of star topology and it takes less than 15 minutes.