I am writing a UDP test client/server and i want to get it through firewall. Supposedly all i need to do is have both sides send to the correct IP and server. Getting an IP is not a problem but how do i have the client pick a random free port and report it to the user? I eventually would want it to connect to a matchmaker server but right now i need a simple working prototype and i would like to cout the port number so my friend/tester can send me the # via IM so we can test.
How do i get the port number?
sorry for the long desc. I notice people tell me not to do what i am asking when i dont give a desc 🙁
To use the highly technical term, this is actually a pretty icky problem or even a pair of icky problems. Depending on the configuration of the firewall, it will usually allow responses from another endpoint on the IP endpoint as the request came from. So… if you friend receives the UDP datagram using something like the
recvfrom()system call, the address parameter will receive the IP endpoint information to respond to. So the other end should be able to respond with asendto()using the same addressing information. Something like:The
peeraddron the other side will be your external address or, more correctly, the IP address of your firewall and the port number that it chose to use. The port number that you specify in your code may be completely different than the port that your friend would have to send data to. Ultimately, it might not matter what port you choose to use since the firewall might be sending and receiving on an entirely different port – this is what Network Address Translation is all about. I would recommend reading RFC3235 for some tips on how to overcome that hurdle.The best approach IMHO is to:
bind()with a zero port number or skipping the bind altogetherrecvfrom())Of course, all of the magic is in the last step. If you can disable NAT or ensure that the firewall is never going to switch ports, then nailing down a port number and
bind-ing to it will work as well. You might want to take a look at%WINDIR%\system32\drivers\etc\services(or/etc/servicesdepending on your OS inclination) to get an idea of what port numbers are reserved or generally in use.