How WebRTC Applications Gather ICE Candidates

WebRTC applications use the Interactive Connectivity Establishment (ICE) framework to discover the most efficient network path for establishing a peer-to-peer connection. This article provides a clear, step-by-step explanation of how a WebRTC application gathers ICE candidates, detailing the roles of host interfaces, STUN servers, and TURN servers in identifying viable network pathways.

Step 1: Initializing the RTCPeerConnection

The process begins when the WebRTC application instantiates an RTCPeerConnection object. During this initialization, the application passes a configuration object containing the URLs of STUN (Session Traversal Utilities for NAT) and TURN (Traversal Using Relays around NAT) servers. These servers are crucial for discovering network paths outside of the local private network.

Step 2: Querying Local Interfaces (Host Candidates)

Once the connection process starts—typically triggered by calling setLocalDescription()—the browser immediately begins gathering Host Candidates. The browser queries the operating system for all active physical and virtual network adapters (such as Ethernet, Wi-Fi, and VPN interfaces). The IP addresses and ports associated with these local adapters are compiled as the first set of ICE candidates.

Step 3: Querying STUN Servers (Server Reflexive Candidates)

To connect with peers outside the local network, the application must discover its public IP address. The browser sends binding requests to the configured STUN servers. The STUN server receives the request, identifies the public IP address and port from which the packet originated, and sends this information back to the browser in a response. The browser packages this public-facing address as a Server Reflexive (srflx) Candidate.

Step 4: Querying TURN Servers (Relay Candidates)

In restrictive network environments where firewalls or symmetric NATs block direct peer-to-peer connections, a relay server is required. The browser sends an allocation request to the configured TURN servers. The TURN server allocates a dedicated public IP address and port on its own system to relay media for the client. The browser packages this relay address as a Relay (relay) Candidate.

Step 5: Emitting and Signaling Candidates

As the browser discovers each ICE candidate, it does not wait for the entire process to finish. Instead, it fires the onicecandidate event handler in real-time.

For every triggered event, the WebRTC application extracts the candidate data and sends it to the remote peer via its signaling channel (usually implemented using WebSockets). This asynchronous transmission process, known as Trickle ICE, allows the remote peer to begin testing connectivity pathways immediately, significantly speeding up the connection establishment time.