By Admin on Thursday, 19 August 2021
Category: All

Delphi STUN/TURN Server and Client (4/4)

From sgcWebSockets 4.5.2, you can build your own STUN/TURN Server and Clients using sgcWebSockets library.

STUN

Session Traversal Utilities for NAT (STUN) (acronym within an acronym) is a protocol to discover your public address and determine any restrictions in your router that would prevent a direct connection with a peer.

The client will send a request to a STUN server on the Internet who will reply with the client's public address and whether or not the client is accessible behind the router's NAT.

TURN

Some routers using NAT employ a restriction called 'Symmetric NAT'. This means the router will only accept connections from peers you've previously connected to.

Traversal Using Relays around NAT (TURN) is meant to bypass the Symmetric NAT restriction by opening a connection with a TURN server and relaying all information through that server. You would create a connection with a TURN server and tell all peers to send packets to the server which will then be forwarded to you. This obviously comes with some overhead so it is only used if there are no other alternatives.

Build a STUN/TURN Server 

​The process to create a STUN/TURN Delphi Server is very simple, just create a TsgcTURNServer and configure the following properties:

Handle the event OnSTUNRequestAuthorization to set the password when a TURN client sends a Request.

Finally set Active property to True to start the server.

Find below a sample configuration where STUN requests doesn't require authorization and TURN requests require Long-Term credentials.

Build a STUN/TURN Client 

​Create a new Delphi STUN/TURN Client is as simple as a Server. Just create a TsgcTURNClient and configure the following properties:


Allocate IP Address

TURN Protocol allows to use a Relayed IP Address to exchange data between peers that are behind NATs.

To create a new Relayed IP Address on a TURN server, the client must first call the method Allocate, this method sends a Request to the TURN server to create a new Relayed IP Address, if the TURN server can create a new Relayed IP Address, the client will receive a successful response. The client will be able to communicate with other peers during the time defined in the Allocation's lifetime.

​The lifetime can be updated to avoid expiration using the method Refresh. The Lifetime is the number of seconds to expire. If the value is zero the Allocation will be deleted.

TURN Server 

This browser does not support the video element.

Compiled TURN Server / Client Demo 

Related Posts