WebRTC Demystified (Part 5)

STUN and TURN Servers
Published on 2024-10-22
Table of ContentsIcon showing table of contents is not open

Hello y'all!

Welcome back to the fifth part of our WebRTC Demystified series! In our previous post, we explored the WebRTC Data Channel which enables real-time peer-to-peer (P2P) communication. Today, we're shifting our focus to two equally critical components that help WebRTC navigate through complex network conditions: STUN and TURN servers.

Whether you're a developer working with WebRTC or someone just curious about how real-time connections work, these two terms are essential for understanding how WebRTC reliably connects peers across different networks.

By the end of this post, you'll have a clear understanding of how these servers operate and how they can help your WebRTC applications establish reliable connections. Let's dive in!

Warning

We're going to get deep into technical terms and may be using jargon to explain things. Read at your own risk, and let us know if you'd like us to break it down further. Your feedback is what keeps us from turning into robots! 🤖

Recap: ICE Candidates and the Challenge of NAT

Before we get into STUN and TURN, let's revisit what we covered in Part 3, where we explored ICE (Interactive Connectivity Establishment) candidates. As a quick refresher, ICE candidates are potential connection paths between WebRTC peers.

However, establishing these connections isn't always straightforward. Most devices are behind firewalls or NATs (Network Address Translation), which hide the device's real IP address. NAT allows multiple devices on a private network (like your home Wi-Fi) to share a single public IP address on the internet. While NAT is great for network security, it poses a challenge for WebRTC—your peer's device can't simply discover your real IP and connect to you.

This is where STUN and TURN servers come in, helping WebRTC peers navigate through NATs and firewalls to establish reliable connections.

What is a STUN Server?

STUN stands for Session Traversal Utilities for NAT. While it may sound complex a STUN server performs a relatively simple task—it helps a device figure out its public IP address and port number.

Let's break it down:

  • NAT Traversal: If your device is sitting behind a NAT, it only knows its private IP address (e.g. 192.168.x.x). A STUN server is located on the public internet and is used by your WebRTC client to determine the public IP address assigned by your internet service provider (ISP).
  • Peer Connection Setup: Once your WebRTC client knows its public IP, it can share this information as an ICE candidate with the other peer, enabling direct communication. The STUN server enables both peers to see beyond their private networks and connect on the public internet.

For example, imagine you're on a video call. Your device is behind a NAT, but by using a STUN server, it can obtain its public IP and share it with the other participant. If the other participant is also able to determine their public IP, the two devices can establish a direct connection, ensuring fast and efficient peer-to-peer communication.

However, while STUN servers are lightweight and efficient, they aren't always enough. If your NAT is particularly restrictive, you may need something more powerful than STUN alone, this is where TURN servers come into play.

What is a TURN Server?

TURN stands for Traversal Using Relays around NAT, and unlike STUN, TURN servers take on a much bigger role in the connection process.

While STUN helps discover public IPs to establish direct peer-to-peer communication, TURN acts as a relay when direct communication isn't possible. This can happen if:

  • Both peers are behind particularly restrictive NATs or firewalls (e.g., corporate or hotel networks).
  • STUN can't provide a workable route, meaning the peers can't connect directly.

In these cases, WebRTC falls back to TURN, where the TURN server relays all communication between the two peers. Instead of connecting directly, the data (such as video and audio) is routed through the TURN server, which sits between the two devices.

    How TURN Works:
  1. A WebRTC client connects to the TURN server, which assigns it a public relay address.
  2. This relay address is shared with the other peer as an ICE candidate.
  3. The other peer also connects to the TURN server using this address, allowing the server to relay all communication between the two clients.

For example, imagine you're on a video call again, but this time both participants are in environments where the NAT is very restrictive—perhaps you're both at different offices with strict firewalls. In this case, STUN won't be enough. The TURN server steps in, acting as a middleman for the entire conversation, ensuring the data can still flow between the two peers, even if it has to take a longer, indirect route.

The downside? Since all traffic is relayed through the TURN server, it consumes more bandwidth and resources compared to a direct connection. This makes TURN more expensive and resource-heavy to operate. However, it's essential in situations where STUN can't establish a direct connection.

Innovative Solutions, Delivered by compose.us

At compose.us, our experienced developers turn your ideas into innovative solutions.

Launch your next project with us.

View Our Portfolio
Team

STUN vs. TURN: When Should You Use Each?

Both STUN and TURN are crucial for WebRTC connectivity, but their roles differ:

  • STUN is used when a direct P2P connection is possible. It's lightweight, fast, and perfect for most WebRTC connections, especially when dealing with simple home networks or lightly restrictive NATs.
  • TURN is used as a last resort, when STUN can't establish a direct connection due to restrictive NATs or firewalls. While necessary in many cases, TURN is more resource-intensive because it relays all communication through the server, so it's used sparingly.

A typical WebRTC session will first attempt to establish a direct connection via STUN, falling back to TURN only if necessary.

STUN and TURN in Action

To better illustrate the use of STUN and TURN servers, let's look at some code examples.

The following configuration tells the WebRTC client to use a STUN server to discover its public IP and port.

const configuration = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' } // Public STUN server
  ]
};

const peerConnection = new RTCPeerConnection(configuration);

Here, we configure the WebRTC client to use a TURN server, providing the necessary credentials to access it.

const configuration = {
  iceServers: [
   	{ urls: 'stun:stun.l.google.com:19302' },
    { 
      urls: 'turn:turnserver.example.org', 
      username: 'user', 
      credential: 'password' 
    }
  ]
};

const peerConnection = new RTCPeerConnection(configuration);

Security Considerations

Both STUN and TURN servers play critical roles in WebRTC connectivity, but TURN servers require extra attention when it comes to security, since they relay actual media data. To ensure privacy and protect against potential attacks, communication between the client and the TURN server must be encrypted. The type of encryption used depends on the underlying transport protocol:

  • DTLS (Datagram Transport Layer Security) is used for UDP-based connections. Since UDP is commonly used in WebRTC for its lower latency, DTLS secures the connection by encrypting the media data exchanged between the client and the TURN server. DTLS ensures that the media streams remain confidential and protected from eavesdropping, even if intercepted.
  • TLS (Transport Layer Security) is used for TCP-based connections. While TCP-based TURN connections are less common in WebRTC, they are still used in certain network environments where UDP is blocked. TLS creates a secure, encrypted tunnel that protects the media streams from being tampered with during transmission.

Additionally, it's important to ensure that only authorized users can access your TURN servers to prevent abuse, overloading, or unauthorized connections.

Wrapping Up: Why STUN and TURN Matter

STUN and TURN servers are often overlooked, but without them, WebRTC simply wouldn't work in many real-world scenarios. By handling the complexity of NAT traversal and firewalls, these servers ensure that WebRTC can provide reliable, real-time communication across different network environments.

Flottform's Handling of STUN and TURN

Flottform simplifies WebRTC connection management, including STUN and TURN configuration. By automatically handling ICE candidate discovery and fallback to TURN when necessary, Flottform ensures your applications connect reliably, without needing to manage these details manually.

With Flottform, you can focus on building great user experiences while we handle the complexities of peer-to-peer connections under the hood.

We'd love to hear how you're using WebRTC and how Flottform can help with your projects! Connect with us on LinkedIn and Twitter / X. Every comment, like, and share fuels our progress!

Cheers,

Newsletter Signup

Do you want to be notified when you can use Flottform yourself? Do you want to receive an e-mail whenever we post updates? Send an e-mail to newsletter@flottform.io to subscribe!