I coded a server/client application which i ran first locally and then over the internet. Therefore i configured my router that it accepts data on port xxxx and forward it to my machine where my server runs and where it accepts connections from client sockets. So everything runs fine and the clients can send there messages to each other. So now my question is, how is it possible that the server can send data to the clients in other networks where port forwarding isn´t activated but when i try it manually it doesn´t work.
I already tried searching about how the TCP saves IPs and ports and I also looked up how the concept of the Internet/TCP/UDP works but couldn´t find an answer to the question.
So first of all I wanted to know that before I implement my server without port forwarding and it would also be appreciated if you could give code examples for c++ on windows if you have any ideas so that i can establish such connections without port forwarding and extern serverhosts on the internet.
Clint -> NAT (router) -> ... -> NAT (router) -> server
When client sends a message (it can be a connection attempt in case of TCP or just a message if it's UDP), its NAT doesn't block it and remembers which local address:port it's coming from and to which address:port it's going to: [client address:port, server address:port]
. When the message hits server's NAT, the NAT knows about your server because you configured "port forwarding" and passes the message to local network. Now, when server sends message back to client and it reaches client's NAT, the NAT checks its internal table, finds a record for this particular server address:port
, retrieves client address:port
part and passes the message to it. So everything works as expected.
It's why usually when you open your browser and go to some web link, you receive server response with web page without problems despite you are behind NAT.
It's a simplified explanation which omits local/global address:port details.