STUN & TURN

IMPORTANT: This document applies only to unbundled usage of Bit6 STUN and TURN services. If you are using Bit6 client SDKs, this functionality is already integrated.

Introduction

ICE protocol, which relies on STUN and TURN servers, provides a mechanism for routing media streams between two clients. It takes care of detecting and traversing firewalls and handling various network configurations.

It is a required component for any WebRTC solution. WebRTC specifications provide more in-depth information.

Prerequisites

Server Integration

Do a REST API call from your server to request ICE configuration information using the API Key and Secret.

You can optionally specify the time-to-live (ttl in seconds) for the returned authentication information. The default TTL is 24 hours.

# Request TURN servers with credentials expiring in 10 minutes (600 seconds)
curl -X POST 'https://api.bit6.com/backend/1/ice?ttl=600' -u apikey:secret

The response will include an array of STUN and TURN servers as well as temporary authentication credentials.

{
  "iceServers": [
    {
      "url": "stun:turn.bit6.com"
    },
    {
      "url": "turn:turn.bit6.com:3478?transport=udp",
      "username": "abc",
      "credential": "xyz"
    }
  ],
  "ttl": 600,
  "expires": 1453845629
}

Send iceServers array to your client-side code.

Client Integration

Request iceServers array from your app server.

Use this array when creating a WebRTC PeerConnection object.

The example below is for JavaScript. iOS and Android code is very similar.

// iceServers is the array returned from your app server
var conf = { 'iceServers': iceServers };
var pc = new RTCPeerConnection(conf);

Code Samples

Node.js

Using the excellent request module.

var request = require('request');

request.post('https://api.bit6.com/backend/1/ice', {json: true}, function(err, resp, body) {
    if (!err) {
        console.log(JSON.stringify(body, null, 4));
    }
}).auth('MyApiKey', 'MyApiSecret', true);
request = require 'request'

opts =
    auth:
        username: 'MyApiKey'
        password: 'MyApiSecret'
        sendImmediately: true
    json: true

request.post 'https://api.bit6.com/backend/1/ice', opts, (err, resp, body) ->
    console.log JSON.stringify(body, null, 4) if !err

PHP

Sample code without any dependencies


$basicAuth = base64_encode( 'MyApiKey' . ':' . 'MyApiSecret');

$context = stream_context_create(array(
    'http' => array(
        'method'  => 'POST',
        'header'  => "Authorization: Basic $basicAuth\r\n" .
                     "Content-type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query(array('ttl' => 600)),
        'timeout' => 5,
    )
));

$ret = file_get_contents('https://api.bit6.com/backend/1/ice', false, $context);

if (false !== $ret) {
    var_dump($ret);
}