0
votes

I'm trying to implement NAT hole punching with boost::asio. By my understanding, NAT hole punch works like this (UDP/TCP):

  1. Client A binds to a port and connects to Server S, and Client B does the same.
  2. When S receives both request and matched, it sends the ip and port of A to B, and B to A.
  3. A and B receives each other's ip and port, and now they send a message to each other from the same port and form a connection (because they are expecting a reply?)

So in boost::asio, I was able to achieve step 1-2, but however because both the client is not port-forwarded, if I attempt to connect from one client to the other, it just give me error like "client actively refuse connection" or "No response from client" (surprisingly the 2 clients have different error even tho they are using the same function).

And it seems like I can't run any asio::async_write without a successful async_connect or asio::tcp::socket::connect. And of course, both of these connect function gives me error when the destination port is not forwarded.

So how can I implement NAT hole punching in this situation, am I missing something in boost::asio? Any help is appreciated! Thank you.

1
I suggest you improve your question, add some examples, some code and make it more clear, Have a look here => How to create a Minimal, Reproducible ExampleFederico Baù
Hi, I've edited some more info on what functions i was using. May I know what is not clear in the question for you? thanks!Sam Stark
Sam, the question its self is pretty good man, what I meant is if you have some code to share is more suitable for Stack Overflow Guidelines. Unfortunately I'm not able to answer your question as I am not a C++ developer, but I know Stack Overflow and how it works pretty well. You should give always some of your source code, so that user expert in the area (C++ in this case) can better help you, Not only you will get a quicker answer, but Also more quality answer and avoid to get downvote and even close the question if is not clear enough. Is just an adviceFederico Baù

1 Answers

1
votes

Based on the "client actively refuse connection" error I assume you're trying a TCP connection. There is fundamental difference in how UDP and TCP hole punching works.

3. A and B receives each other's ip and port, and now they send a message to each other from the same port and form a connection (because they are expecting a reply?)

This is NOT how TCP hole punching works. Since TCP is point-to-point, in step 3 you have to predict the next incoming port of either A or B, and A or B need to try to establish a new connection using the predicted port of the other side. Obviously there are many different NAT implementations, and it is not always possible to reliably predict the port allocation, especially in case of carrier-grade NAT. Refer to TCP hole punching for further details. As an alternative to TCP hole punching, have a look into UPnP to add a port forwarding.