Share2Me

Back to Articles
Tech Deep Dive

Under the Hood: How WebRTC Coordinates Direct P2P Connections

K

Kamal Tripathi

Founder & Lead Engineer, Share2Me

Tech Deep DiveJuly 5, 202615 min read

WebRTC (Web Real-Time Communication) has revolutionised the web by enabling direct peer-to-peer connections between browsers without plugin installations. While most users associate it with video conferencing, its RTCDataChannel component is a powerful tool for secure, serverless file transfer. Understanding how WebRTC works under the hood is valuable for developers building real-time applications and for curious users who want to understand exactly what happens when they share a file using a P2P service. In this technical deep dive, we walk through the complete connection lifecycle: SDP signaling, ICE negotiation, STUN and TURN traversal, DTLS handshakes, and SCTP data streams.

1. The Signaling Phase: Session Description Protocol (SDP)

WebRTC cannot establish a direct connection without an initial metadata exchange called the signaling phase. During signaling, the two peers exchange Session Description Protocol (SDP) documents. An SDP document is a structured text file that describes the peer's network configuration, supported media formats, cryptographic fingerprints, and ICE candidates. The initiating peer generates an 'SDP Offer' by calling pc.createOffer() on its RTCPeerConnection object. This offer is then sent to the remote peer via an out-of-band signaling channel — typically a WebSocket connection to a signaling server. The remote peer receives the offer, sets it as the remote description, generates an 'SDP Answer' by calling pc.createAnswer(), and sends it back via the same signaling channel. WebRTC's spec deliberately leaves the choice of signaling mechanism open — any transport that can relay text messages can work. Share2Me uses Socket.io WebSockets on a Node.js server as its signaling transport. Once the offer/answer exchange is complete, the signaling server's role is finished — it does not participate in subsequent data transfer.

  • SDP Offer: Contains the initiating peer's IP candidates, DTLS fingerprint, and supported codecs.
  • SDP Answer: The remote peer's matching configuration, used to complete the connection parameters.
  • Signaling Agnostic: WebRTC spec does not mandate a signaling transport — WebSockets, HTTP polling, or even QR codes can work.
  • Server Role Ends: After the SDP exchange, the signaling server is not involved in data transfer.

2. ICE Negotiation: Finding the Best Connection Path

After the SDP exchange, both peers must actually locate each other on the network. This is the job of ICE — Interactive Connectivity Establishment. ICE works by having each peer gather a list of 'ICE candidates' — potential network endpoints through which data might be routed. There are three types of ICE candidates. Host candidates are the device's local IP addresses (e.g., 192.168.1.5:50000). Server-reflexive candidates are discovered by querying a STUN server — the STUN server reflects back the device's external public IP and port as seen from the public internet. Relayed candidates are allocations on a TURN relay server, used as a last resort when direct connections are blocked by strict NAT or firewall rules. As candidates are gathered, they are sent to the remote peer via the signaling channel (a process called ICE Trickle). Both peers attempt to establish connections using all candidate pairs simultaneously, and the ICE agent selects the lowest-latency pair that succeeds. In typical consumer network configurations, a server-reflexive candidate pair (STUN) will succeed. Only in enterprise networks with highly restrictive symmetric NAT firewalls will the connection fall back to a TURN relay.

  • Host Candidates: Local LAN IP addresses — fastest, used when both peers are on the same local network.
  • Server-Reflexive: External IP/port as seen by a STUN server — used for most internet-based connections.
  • Relayed: TURN relay allocation — encrypted fallback for symmetric NAT environments like corporate networks.
  • ICE Trickle: Candidates are sent and tested incrementally, reducing connection establishment latency.

3. DTLS Handshake: Establishing Encrypted Transport

Once the ICE candidate pair is selected and a UDP path is established between the peers, WebRTC performs a DTLS (Datagram Transport Layer Security) handshake on top of that UDP path. DTLS is essentially TLS adapted for unreliable datagram (UDP) transport. The DTLS handshake establishes mutual authentication using the cryptographic fingerprints exchanged in the SDP documents, and negotiates the symmetric keys for encrypting all subsequent data. This is what makes WebRTC traffic inherently encrypted — even if you route WebRTC traffic through a TURN relay, the TURN server only sees the encrypted DTLS ciphertext and cannot read the data. After the DTLS handshake, SRTP (Secure Real-time Transport Protocol) is used for media streams and SCTP over DTLS is used for DataChannels. The DTLS session is authenticated using the fingerprints in the SDP documents that were exchanged earlier, which prevents man-in-the-middle attacks — if a MITM modifies the SDP to inject their own DTLS fingerprint, the handshake will fail because the fingerprints no longer match.

4. RTCDataChannel and Binary File Streaming

With the DTLS-secured SCTP session established, the application can create RTCDataChannels. A DataChannel is created with pc.createDataChannel('label', options). The options include a boolean 'ordered' flag (true for guaranteed ordering, which is required for file transfers) and a 'maxRetransmits' setting. For file transfers, ordered reliable mode is mandatory — a single out-of-order or lost packet in a binary file corrupts all subsequent data. The file is read by the browser using the FileReader API or the modern File System Access API, sliced into binary ArrayBuffer chunks (typically 64 KB to 256 KB), and each chunk is sent via dc.send(chunk). The receiver reconstructs the file by accumulating chunks in order. WebRTC DataChannels do not have a built-in framing mechanism for multi-file transfers or metadata — the application layer (Share2Me's JavaScript code) implements a custom protocol on top of the DataChannel, sending a JSON header message first that specifies the file name, size, total chunk count, and MIME type, followed by the binary chunk stream.

  • SCTP Protocol: WebRTC DataChannels use SCTP over DTLS for reliable, ordered binary data delivery.
  • Ordered Reliable Mode: Essential for file transfers — out-of-order chunks corrupt binary files.
  • Application-Level Framing: The application must implement its own protocol for file metadata and multi-file sessions.
  • Backpressure: The DataChannel's bufferedAmount property allows the application to implement flow control and avoid buffer overflow.

Conclusion

A complete WebRTC data transfer involves multiple protocol layers: HTTP WebSocket signaling, SDP offer/answer exchange, ICE candidate gathering and negotiation, STUN/TURN traversal, DTLS mutual authentication, and finally SCTP data delivery. Each layer solves a specific problem in establishing a secure, direct, low-latency connection across the public internet. Understanding this protocol stack helps developers build more robust real-time applications and helps users appreciate what is happening behind the scenes when they share a file using a P2P service.

K

Written by Kamal Tripathi

Founder & Lead Engineer, Share2Me

Kamal is the founder of Share2Me and a full-stack engineer specialising in real-time browser communications, WebRTC, and cryptographic systems. He built Share2Me to solve the problem of cross-platform, privacy-first file sharing without requiring app installations.

Last updated: August 10, 2026