Can you get which source port the client has connected from?

As stated in the FAQs, clients, each time they connect to a server, specifying their port, are given an Ephemeral port, that is each time different, for their local endpoint. This is comparable to having a UdpClient object with empty constructor.

Once sent the first udp packets to the server, is there a way to know from the client which local port (i know the remote port may be different) has it bound to?

I tried by using myUtpObject.ConnectionData.ListenEndPoint.Port but doesn’t seem to be considered at all by clients

Using Netcode for GameObjects (NGO), I don’t think this is possible. The Unity Transport package itself offers this through the NetworkDriver.GetLocalEndpoint API, but unfortunately that’s not exposed through the wrapper in NGO.

If I may ask, why do you need access to this information?

Basically, to open a first connection between peers (a NAT punch-through implementation), by sending a packet from the same port to a node server.

Thanks for the answer. That seems like a very sensible use case. I’ll file something on our end to expose this information. In the meantime, you can provide your own extension to UnityTransport to expose the functionality.

Create a script with the following contents:

using Unity.Networking.Transport;

namespace Unity.Netcode.Transports.UTP
{
    public partial class UnityTransport
    {
        public ushort GetLocalPort()
        {
            // Use GetLocalEndpoint instead if using Transport 2.0.
            return m_Driver.LocalEndPoint().Port;
        }
    }
}

And then create an assembly reference so that this script gets included in the Unity.Netcode.Runtime assembly. You should then be able to use this new method to get the local port being used (of course this will only be available after the client has started).

1 Like

Thank you, the extension works as expected!
In the meantime i managed to get this port by checking every udp listener’s port before and after setting up connection (not really reliable, even if it worked out), but this extension is a much cleaner solution.