Thursday, November 26, 2015

NAT Traversal or how to make P2P on Android

Many of us used BitTorrent(or uTorrent) to download files on internet in a short time. Their download speed is high due to Peer-to-peer technology. That means, rather than downloading file from server, we are getting the file from another computer.
But how two computers that have a local IP and are behind NAT, how they can connect each other?
For that, NAT Traversal methodologies come for help.
Note that there are mainly 2 types of NAT:
Symmetrical(complex NATs:carrier-grade NAT) and Full (home network or small enterprises).
let us consider Full NATs first.

Methodologies of NAT traversal are:
UPnP - old and hardware oriented method
NAT-PMP (later succeeded by PCP)- introduced by Apple, also hardware oriented(i.e: not all routers have it, and even if it had, it is turned off by default)
UDP Punching  - this is done by STUN which uses public server to discover NAT public IP & port
TCP Punching -  similar to UDP punching but more complicated

Symmetrical NATs are a big issue. They are hard to be punched as they changed router ports randomly. So there is a tiny chance to establish connection.
There are some approaches which can help, but practically difficult to implement:
"Large Scale Symmetric NAT Traversal with Two Stage Hole Punching":
https://drive.google.com/file/d/0B1IimJ20gG0SY2NvaE4wRVVMbG8/view
Fortunately, Symmetrical NATs are being used only in security restricted areas, and are getting less popular because people are understanding how P2P is important.

So, how we can practically make P2P connection on Android.
I found 2 ways, one to use libraries (harder) and another WebRTC(easier).
Libraries:
https://github.com/jitsi/ice4j
https://github.com/htwg/UCE

WebRTC:
As you know, webRTC uses p2p and internally it has ICE(that combines STUN and TURN) protocol to establish p2p connection.
This option is easier to use because webrtc library takes care of future updates and it is a new cool standard.
https://github.com/pchab/AndroidRTC


References:
http://stackoverflow.com/questions/9656198/java-udp-hole-punching-example-connecting-through-firewall?rq=1
https://en.wikipedia.org/wiki/STUN
https://en.wikipedia.org/wiki/UDP_hole_punching
http://chimera.labs.oreilly.com/books/1230000000545/ch04.html
http://stackoverflow.com/questions/12359502/udp-hole-punching-not-going-through-on-3g?rq=1
Theory: http://www.bford.info/pub/net/p2pnat/index.html#SECTION00040000000000000000
Tutorial on ice4j: http://blog.sharedmemory.fr/en/2014/06/22/gsoc-2014-ice4j-tutorial/

No comments:

Post a Comment