lsalzman / enet

ENet reliable UDP networking library
MIT License
2.73k stars 670 forks source link

NAT punching with ENet #201

Closed lolriven closed 2 years ago

lolriven commented 2 years ago

Hello, I'd like to know which steps I could take using ENet to punch through NAT.

I'm aware of what's involved when it comes to NAT traversal.

1)I have a public server( NAT Server ) which allows incoming connections. 2)This server hands out public IP of clients who connect. 3)Those clients can then use those ip to connect to eachother

I've solved step 1 and 2. But step 3 is where I'm stuck. I'm aware in regular raw UDP sockets, I don't close the socket which was used to initially send packets to the NAT Server, rather I use that same socket and spam packets to other clients until traversal is established.

But because ENet is connection oriented or at least seems that way, I'm not sure how to process it.

I'm attempting to use the same socket which was created for the NAT Server connection to then connect to remote peers. But I'm unsure if this is the right steps because I can't seem to punch through.

This is my initial socket

    addresshost.host = ENET_HOST_ANY;
    addresshost.port = 11753;
    client = enet_host_create (NULL /* create a client host */,
                               5 /* only allow 1 outgoing connection */,
                               2 /* allow up 2 channels to be used, 0 and 1 */,
                               0 /* assume any amount of incoming bandwidth */,
                               0 /* assume any amount of outgoing bandwidth */
                               );

I bind it on port 11753.

I connect to the NAT server also using ENet.

    ENetAddress address;
    ENetEvent event;
    ENetPeer *peer;

    enet_address_set_host (& address, "NATserver.ip");
    address.port = 8011; //NAT server port

    peer = enet_host_connect (client, & address, 2, 0);

Then I receive the other clients IP and attempt to connect to them after wards on port 11753

        ENetAddress remoteaddress;
        ENetEvent remoteevent;
        ENetPeer *remotepeer;
        enet_address_set_host (& remoteaddress, "remoteclient.ip");
        remoteaddress.port = 11753;//client ip to connect to 
        remotepeer = enet_host_connect (client, & remoteaddress, 2, p);

And this is where it fails, it's unable to connect to the remote client even if I call it in a loop .

Am I not supposed to call enet_host_connect again?

I'm confused here.