开发者

Communicate to public IP from a local network (WinSock, C)

I'm new 开发者_如何学Cto this forum (at least at asking questions), so please be patient. I'm trying to write simple client-server applications to communicate using datagram (UDP) sockets, with C and Windows.

The scenario is very simple, I want to be able to send/receive data from a machine in some local network (behind a GATEWAY/NAT) to some host having public IP. I can send the data, but it seems impossible to receive any data back, because the remote server can't see the client's local IP.

I don't want the user to perform manual port forwarding on the GATEWAY, and I also don't want to use UPnP because of security issues (though it also should be enabled by the user).

I think it is possible because applications like Skype or Browsers can do it, but how ? Are there some automatically forwarded ports or things like that ? I'm exhausted of searching the web ... PLEASE HELP !


For UDP connections, most home NAT gateways will automatically create a temporary reverse mapping for each outbound packet.

Consider a scenario where your client is running on the internal machine with IP address 192.168.4.5, sending a UDP packet from port 65000 to the external address 64.34.119.12:6789, via a gateway with external IP address 192.0.43.10. When the gateway sees your internal client send a UDP packet from 192.168.4.5:65000 to the external address, it will NAT it to an external address and port, like 192.0.43.10:5500. Your server will see a packet with a source address of 192.0.43.10:5500 and destination address 64.34.119.12:6789. The router also sets up a reverse mapping, so that if it sees a packet arrive on the external interface with a source of 64.34.119.12:6789 and a destination of 192.0.43.10:5500, it will redirect it back to 192.168.4.5:65000. This mapping typically times out after a short while.

This means that in simple cases, all you need to do is:

  1. On the client, use the same port to send to the server and listen for responses;
  2. On the server, respond to the client at the address and port that the client's packet was receieved from, using the same server port that recieved the packet;
  3. Have the client send the initial packet in the conversation;
  4. Don't leave the "connection" idle for more than a few minutes at a time.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜