I’m trying to implement NAT punch through for port-restricted NAT’s. I can do the punch though okay, but the problem is how to tell UNET the source port to use when connecting to the server. For instance, if I connect to a server on port 7777 and inspect the client process I see that it has randomly picked a source port (53692 in this case).
What I’d like to do is to be able to do NAT punch through on a port I pick (say, 51000), then tell UNET “connect to server x on destination port 7777 with source port 51000.” (The socket equivalent of this is binding a socket to a local endpoint with a specified port). But even the low level API in UNET doesn’t seem to expose this (I’ve gone over the documentation several times but maybe I’ve missed it?).
Does anyone have any idea how to do this? Or even if I could get the source port UNET is using after the fact?
Thank you. I did figure this out eventually, however it didn’t help me because what I really want is to use the high-level API (NetworkManager, NetworkClient, NetworkConnection, etc.). Even though the connectionId and hostId values can be changed via the NetworkConnection object, calling NetworkClient.Connect( … ) will always internally create and use a new Host/socket with port=0.
I know this is an old post but I’m trying to do the exact same thing now and running into the same problem. I’m so close to having the punchthrough working, I just can’t figure out how to hook into the HLAPI. I’m on 5.4.0b3 is there any way I can set the port that NetworkClient connects from?
Holy Crap I think I actually figured this out. It’s a nasty little trick but it seems to be working. Instead of trying to set the port that the client uses to connect (which seems to be impossible) I tried setting the transport level host id instead. So first:
For anyone unfamiliar, I’m using reflection to set the private field m_ClientId on the NetworkClient. It seems this has to be done after calling Connect since that is where unity sets it internally. It’s likely that there will now actually be two transport level hosts, but it doesn’t really matter. When the connection succeeds and the NetworkClient initializes its NetworkConnection object it does so with the proper hostId and connectionId so it seems like everything is set up right.
I’ve actually got this working right now with the NAT Punchthrough from RakNet. I’m able to connect from outside my network with no port forwarding necessary. I wasn’t able to connect without punchthrough or even with punchthrough until I implemented this fix to be able to set the port the client connected from. So I’m like 99% positive this works and the client is actually connecting from the correct port.