Click here to Skip to main content
Click here to Skip to main content

STUN Client

By , 20 Apr 2007
 
Screenshot - stun.jpg

Introduction

STUN - Simple Traversal of User Datagram Protocol (UDP) through Network Address Translators (NATs). In few words, it just helps you to map your local computer IP:port to public IP:port.

STUN working idea is pretty simple. The client just sends a UDP packet out to the STUN server and the server answers back with IP:port you connected. STUN does three tests to detect the NAT type.

In test I, the client sends a STUN Binding Request to a server, 
without any flags set in the CHANGE-REQUEST attribute, 
and without the RESPONSE-ADDRESS attribute. This causes the server 
to send the response back to the address and port that the request came from.
           
In test II, the client sends a Binding Request with both the 
"change IP" and "change port" flags from the CHANGE-REQUEST attribute set.  
              
In test III, the client sends a Binding Request with only the "change port" flag set.
                          
                                    +--------+
                                    |  Test  |
                                    |   I    |
                                    +--------+
                                         |
                                         |
                                         V
                                        /\              /\
                                     N /  \ Y          /  \ Y             +--------+
                      UDP     <-------/Resp\--------->/ IP \------------->|  Test  |
                      Blocked         \ ?  /          \Same/              |   II   |
                                       \  /            \? /               +--------+
                                        \/              \/                    |
                                                         | N                  |
                                                         |                    V
                                                         V                    /\
                                                     +--------+  Sym.      N /  \
                                                     |  Test  |  UDP    <---/Resp\
                                                     |   II   |  Firewall   \ ?  /
                                                     +--------+              \  /
                                                         |                    \/
                                                         V                     |Y
                              /\                         /\                    |
               Symmetric  N  /  \       +--------+   N  /  \                   V
                  NAT  <--- / IP \<-----|  Test  |<--- /Resp\               Open
                            \Same/      |   I    |     \ ?  /               Internet
                             \? /       +--------+      \  /
                              \/                         \/
                              |                           |Y
                              |                           |
                              |                           V
                              |                           Full
                              |                           Cone
                              V              /\
                          +--------+        /  \ Y
                          |  Test  |------>/Resp\---->Restricted
                          |   III  |       \ ?  /
                          +--------+        \  /
                                             \/
                                              |N
                                              |       Port
                                              +------>Restricted

/// <summary>
/// UDP is always blocked.
/// </summary>
UdpBlocked,

/// <summary>
/// No NAT, public IP, no firewall.
/// </summary>
OpenInternet,

/// <summary>
/// No NAT, public IP, but symmetric UDP firewall.
/// </summary>
SymmetricUdpFirewall,

/// <summary>
/// A full cone NAT is one where all requests from the same internal 
/// IP address and port are mapped to the same external IP address and port.
/// Furthermore, any external host can send a packet to the internal host, 
/// by sending a packet to the mapped external address.
/// </summary>
FullCone,

/// <summary>
/// A restricted cone NAT is one where all requests from the same
/// internal IP address and port are mapped to the same external IP address and port.
///  Unlike a full cone NAT, an external host (with IP address X) 
/// can send a packet to the internal host only if the internal host 
/// had previously sent a packet to IP address X.
/// </summary>
RestrictedCone,

/// <summary>
/// A port restricted cone NAT is like a restricted cone NAT, but the restriction 
/// includes port numbers. Specifically, an external host can send a packet, 
/// with source IP address X and source port P, to the internal host only if 
/// the internal host had previously sent a packet to IP address X and port P.
/// </summary>
PortRestrictedCone,

/// <summary>
/// A symmetric NAT is one where all requests 
/// from the same internal IP address and port, 
/// to a specific destination IP address and port, are mapped to the same external 
/// IP address and port.  If the same host sends a packet with the same source address 
/// and port, but to a different destination, a different mapping is used. 
/// Furthermore, only the external host that
/// receives a packet can send a UDP packet back to the internal host.
/// </summary>
Symmetric

Using the Code

// Create new socket for STUN client.
Socket socket = new Socket
    (AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any,0));

// Query STUN server
STUN_Result result = STUN_Client.Query("stunserver.org",3478,socket);
if(result.NetType != STUN_NetType.UdpBlocked){
    // UDP blocked or !!!! bad STUN server
}
else{
    IPEndPoint publicEP = result.PublicEndPoint;
    // Do your stuff
}

History

  • 20.04.2007 - Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ivar Lumi

Estonia Estonia
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: different results on different serversmemberprince prince21-Jul-08 3:46 
I tried testing with JSTUN client, it gives the expected result in terms of response FullCone, RestrictedCone.. But it does not give the IP address and the mapped port. May be there is problem with the flow of the algorithm implemented in your client?
GeneralRe: different results on different serversmemberIvar Lumi21-Jul-08 7:31 
Does jstun gives different results for same LAN with diferent stun servers ?
GeneralSTUN client on WM5memberprince prince27-Jun-08 0:25 
Hi,
would this project work fine if I try to recompile for compact framework ?if not what modifications do I need. I understand that the forms are not the same since WM5 is based on WinCE but would the client work fine?
GeneralRe: STUN client on WM5memberIvar Lumi27-Jun-08 4:14 
Hi,
 
STUN client must work, at first look it doesnt uses classes what CF wont support.
GeneralAny server help create tunnel between 2 peer behind NATmemberhoanglinh94668-Jun-08 23:32 
The NAT server only let us know about our server-side ip and port. But when each peer know its server-side ip and port, they need to send that information to each other, right ? And they cannot send directly to each other, so do u know any server do that (we can connect to that server, send our information, and server send that information to the other peer...) ?
 
Thank you very much !
GeneralFirewall is not blocking UDP but Stun Client demo program shows UDP is blockedmemberSrein5-Jun-08 13:47 
I have STUN server and running the stun client demo program from outside the firewall. I get the NAT type as UdpBlocked but I have Wireshark running on the firewall machine and it shows UDP is transmitted. What do you think the problem? Thanks for the excellent program
GeneralRe: Firewall is not blocking UDP but Stun Client demo program shows UDP is blockedmemberIvar Lumi5-Jun-08 19:34 
Transmited won't mean not blocked, like response packet never reaches, so firewall wont allow resonses back from server.
GeneralI want to make a file transfer program !! Help mememberhoanglinh94664-Jun-08 21:30 
I want to make a file transfer program using STUN to pass through NAT, but I think UDP protocol isn't suitable for this, right ? And I can't find any STUN for TCP. So do you have any suggestion for me ? Do I have to build a protcol like TCP based on UDP ???
 
Thanks.
GeneralRe: I want to make a file transfer program !! Help mememberIvar Lumi5-Jun-08 4:47 
TCP cant be used behind NAT ....
 
You must use UDP. The only way it packetize file in to UDP chunks and add checksum for each chunk. SO you only need to make some logixc what keeps track what chucks not reaced ant retransmit them. md5 chek sum quarrantees that chunk data not corrupt.
QuestionCan it make port mapping with STUN ?memberBigbermusa30-May-08 4:21 
Hi,
 
I want to transfer audio and text to the clients over the internet,with STUN can it make this for me to do port mapping behind a LAN between two machines ?
 
Thank you.
 
Bigbermusa
AnswerRe: Can it make port mapping with STUN ?memberIvar Lumi30-May-08 5:24 
Hi,
 
Yes, thats the main usage of STUN.
GeneralRe: Can it make port mapping with STUN ?memberBigbermusa30-May-08 6:13 
OK,thanks.
Can it also support for sending/receiving video packet ?
How long that stunserver will be site situation on the net ?
 
Thanks,
Bermusa
GeneralRe: Can it make port mapping with STUN ?memberIvar Lumi30-May-08 7:14 
>Can it also support for sending/receiving video packet ?
Seems you have get wrong idea about stun. stun is just for discovering pubic ip and port of NAT behind IP endpoint.
Most common video transport is RTP.
 
>How long that stunserver will be site situation on the net ?
I think if you reread your question, then even you dont get what you mean by this.
GeneralRe: Can it make port mapping with STUN ?memberBigbermusa30-May-08 7:29 
Ivar Lumi wrote:
>Can it also support for sending/receiving video packet ?
Seems you have get wrong idea about stun. stun is just for discovering pubic ip and port of NAT behind IP endpoint.
Most common video transport is RTP.

 
OK,i see,but let me ask you that if port of NAT is discovered and mapped by stun,can i use it to transport video stream over the internet ?
If i'm wrong understanding,please suggest.
 
Thanks,
Bigbermusa
GeneralRe: Can it make port mapping with STUN ?memberIvar Lumi30-May-08 7:39 
Theoretically you can when both computers start sending data each other. Otherwise NAT won't pe opened !!!
Normally some kind of signalling protocol is used to setup session. For example voip phones use SIP + SDP for that.
GeneralRe: Can it make port mapping with STUN ?memberBigbermusa30-May-08 8:09 
That's mean only port mapping by stun but NAT won't be opened to point correctly,like you said.
Is it right ?
GeneralRe: Can it make port mapping with STUN ?memberIvar Lumi30-May-08 9:12 
NAT is opened(only for remote target) after you send out initial request to target.
And from there: if both endpoints behind NAT, both must send data to each other to make actual data flow.
(computerA - NAT - INTERNET - NAT - computerB)
GeneralRe: Can it make port mapping with STUN ?memberBigbermusa30-May-08 10:00 
Let me know again,if stun client run on both that mean they're the remote target where NAT is also opened by stun for each remote (that's incoming host)after that if they need to communicate both must send data ie. external ip and port to each other then they can make actual data flow on the network.
Is i right understanding ?
 
Thanks,
Bigbermusa
GeneralRe: Can it make port mapping with STUN ?memberIvar Lumi30-May-08 10:05 
stun is not related to data sending.
For example if you know your remote end point and remote end poiny knows yours, you both start sending, then NAT opened.
 
For example you make stun request what happens ony:
yourStunRequest -> NAT(nat is opened for stun server response) -> STUN
 
Sedning data by alone, data bever reaches, remote NAT holds it.
yourData -> NAT(nat opened for remote end point only) -> NAT --- xxxx remote
But if both send, then both nats will open.
GeneralRe: Can it make port mapping with STUN ?memberBigbermusa30-May-08 10:29 
Ok,that mean stun make a road or bridge for my data communication if both send to each other and NAT is ok ,right ?
GeneralRe: Can it make port mapping with STUN ?memberIvar Lumi30-May-08 19:38 
I have teold severals times NO.
 
Just read:
http://www.faqs.org/rfcs/rfc3489.html[^]
 
http://en.wikipedia.org/wiki/Network_address_translation[^]
GeneralRe: Can it make port mapping with STUN ?memberBigbermusa30-May-08 19:46 
Ok,thanks.
GeneralSTUN - Small typomemberMigounette23-May-08 23:26 
Section:
 
Nice work, but you made a little mistake regarding the retransmit time.
 
9.3 Formulating the Binding Request
 
Clients SHOULD
retransmit the request starting with an interval of 100ms, doubling
every retransmit until the interval reaches 1.6s. Retransmissions
continue with intervals of 1.6s until a response is received, or a
total of 9 requests have been sent. If no response is received by 1.6
seconds after the last request has been sent, the client SHOULD
consider the transaction to have failed. In other words, requests
would be sent at times 0ms, 100ms, 300ms, 700ms, 1500ms, 3100ms,
4700ms, 6300ms, and 7900ms. At 9500ms
 
Here is my proposal:
 
private static STUN_Message DoTransaction(STUN_Message request,Socket socket,IPEndPoint remoteEndPoint)
{
byte[] requestBytes = request.ToByteData();

// Retransmition table : 9500ms sound that the transaction has failed
int[] retransList = { 0, 100, 300, 700, 1500, 3100, 4700, 6300, 7900, 9500 };
int retransPos = 0;
 
DateTime startTime = DateTime.Now;
 
// We do it only 2 sec and retransmit with 100 ms.
while (retransPos < retransList.Length)
{
TimeSpan diffTime = DateTime.Now - startTime;
 
try
{
if (diffTime.TotalMilliseconds > retransList[retransPos])
{
// It's time for a retransmition
retransPos++;
socket.SendTo(requestBytes, remoteEndPoint);
}
 
// We got response.
if (socket.Poll(20, SelectMode.SelectRead))
{
byte[] receiveBuffer = new byte[512];
socket.Receive(receiveBuffer);
 
// Parse message
STUN_Message response = new STUN_Message();
response.Parse(receiveBuffer);
 
// Check that transaction ID matches or not response what we want.
if (request.TransactionID.Equals(response.TransactionID))
{
return response;
}
}
}
catch(Exception exception)
{
Console.WriteLine("Exception : " + exception.Message);
exception = null;
}
}
 
// Timeout detected or exception
return null;
}
GeneralRe: STUN - Small typomemberIvar Lumi26-May-08 2:17 
Hi,
 
Thats not typo, thats simplified solution.
Normally retransit wont happend in reallife, so if you retransmit 200mx,200ms , ... i dont see any problem about that.
But though it's not 100% RFC comilant ... .
 
Your approach is almost RFC comiplant, but if to splitting hair- -- except:
If no response is received by 1.6
seconds after the last request has been sent, the client SHOULD
consider the transaction to have failed.
QuestionHow to combine with RTC API [modified]memberjan de vries16-Feb-08 7:33 
Ivar, you're very good with all these protocols. Great code!
 
I would like to use your STUN Client in combination with the Microsoft RealTime Communications (RTC) API, because I'm working on a VoIP applicaton. This RTC API provides a number of hooks for plugging in some kind of portmapping functionality.
I found out that, with the help of your STUN Client class, I can create the required portmappings. But the RTC code doesn't seem to be able to use the mapped ports.
The reason could be that I create a socket, which I handover to your STUN Client to get the mapped address and port, but which I have to close before returning the control to the RTC code. Otherwise the RTC code generates an error (which I can understand, since it tries to open a socket on an address and port where another one is open already).
But could it be that the portmapping, created by your STUN Client, is removed from the NAT, the moment I close the socket that I used for creating the portmapping (by calling your STUN Client)?
 
modified on Sunday, February 17, 2008 2:09 AM

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 20 Apr 2007
Article Copyright 2007 by Ivar Lumi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid