heiher / natmap

TCP/UDP port mapping for full cone NAT
MIT License
1.38k stars 103 forks source link

How does stun - http work? #52

Closed vavrecan closed 7 months ago

vavrecan commented 8 months ago

I'm having trouble understanding what this app does. If it's able to make internal network ports, like an HTTP server, accessible despite being behind a NAT, that's fantastic! Does it utilize NAT hole punching? And how does it interact with STUN or an HTTP server?

Could you explain how data is transferred using STUN or an HTTP server? My understanding is that modern routers typically don't allow for anything other than solutions like Rathole (https://github.com/rapiz1/rathole), which requires both a server and a client. How is it that this solution doesn't need that?

Thank you

MikeWang000000 commented 8 months ago

Thank you for your interest in NATMap.

This stun - http method was originally designed by me at Natter, a similar project written in Python, so it might be appropriate for me to explain it.


Let's say we have local IP:PORT A:B. Before we reach STUN server C:D, address A:B will be translated to public address X:Y.

[A:B <--NAT--> X:Y] ---(short)---> C:D (STUN server)

STUN server will tell you your public address X:Y.


However, this is not enough. When we finish the STUN query, the TCP connection closes and the A:B to X:Y translation soon expires.

So we introduce the HTTP connection. This connection also binds to local address A:B, but lasts longer, by sending header Connection: Keep-Alive.

[A:B <--NAT--> X:Y] ---(long)---> E:F (HTTP server)

Up to this point, we have a persistent address mapping A:B to X:Y.

Port A:B can have many outgoing and incoming connections simultaneously by setting flags SO_REUSEADDR and SO_REUSEPORT.

So the third socket also listens to address A:B but accepts incoming connections. People on the Internet visiting port X:Y will finally reach A:B.

[A:B <--NAT--> X:Y] <------ incoming connections