The method most P2P programs use is that of
Hole punching,
where a central server is used to pass information between the two parties
as regarding the ports used.
Using that information, the parties can establish a direct connection to
valid port numbers so that the firewall or router will accept
and forward the incoming packets to the open port.
I believe that your question relates more to UDP over NAT with no intervening
common server, which is the general problem of
NAT traversal.
The problem here is that the NAT device has no automatic method of determining
the internal host for which incoming packets are destined, since the originating
party does not know the port number on which the other party is listening.
Several algorithms were developed for solving that problem of
UDP hole punching.
Some UDP hole punching algorithms depend on both parties using the same ports.
Other algorithms use a temporary TCP connection to pass the information
required for establishing the UDP connection.
Other UDP hole punching
techniques do not require any port information, but use instead algorithms where
both parties will start sending to each other, using multiple attempts,
and accepting the fact that at least the first packets will be lost.
After the first failed attempt, the NAT device has
a record of having sent a packet to the other machine, and so will let through
any packets coming from this IP address and port number.
The algorithm for that is detailed in the above linked Wikipedia article.
This is based on the fact that if a packet is received from an address
to which a connection was previously attempted, then even if it is on a
different port from the one through which the local party tried to establish
the connection, then it will switch it to the right port. This lets the UDP
packet get through the NAT, as the NAT mapping for it was already established
by the local party attempting to send.
The problem with all these methods is that NAT address translation technologies
are not standardized. As a result, the methods used for NAT traversal are often proprietary and poorly documented, and whether they will work or not varies
between routers of different make and model.
The IETF has an entire working group defining what NAT devices should do in order to make the least mess: BEHAVE
There are a several methods of getting data through NAT devices, some listed on the BEHAVE page. There are also STUN, UPnP, NAT-PMP, and Teredo.