The scenario is the following. I have two machines A and B: A: Client (behind NAT) B: Server (behind NAT)
I want B to be able to listen on any given port, so that A
You will have to either:
Set up port forwarding from the nat gateway in front the server into the machine your server software is running, and have the client connect to the IP address of that gateway.
Create a proxy server sitting inbetween the 2 nat gatewys so both your server and client can connect to that. Both your server and client have to set up a connection to that proxy which will mediate the data between those 2 connections.
Hole punching is moderately well-understood for UDP communication, but it can be reliably used to set up peer-to-peer TCP streams as well. Here is the well detailed article on both TCP and UDP:
http://www.brynosaurus.com/pub/net/p2pnat/
An alternative to a proxy server is a match-making server. Instead of proxying all of the traffic, the match maker just negotiates until the peers can talk to each other. This involves finding the external public IPs of the peers and talking to each one so that the firewall/router knows that the peers wish to communicate.
This is called hole punching and it often has to be done by the match maker rather than the peers themselves. Once the hole are punched though, the match maker can tell the peers about each other and they can communicate directly.
To answer the example of Peer to Peer programs, and in general: There is a technology called Universal Plug and Play which NAT routers can use to allow clients behind them to expose ports to the outside. That's what bittorrent clients can use so the other clients can directly connect to them.