TcpClient- how to connect to an external IP addres

2019-06-14 05:00发布

问题:

I have been trying to setup a basic scenario where a TcpClient connects to a TcpListener on the same machine, but so far it only works for 127.0.0.1 and 192.168.X.Y. Here is my code:

var server = new TcpListener(IPAddress.Any, 51328);

server.Start();

var client = new TcpClient();

client.ConnectAsync(IPAddress.Parse("address from whatismyip"), 51328);

server.AcceptTcpClient(); // hangs indefinitely here

Console.ReadKey();

I got my external address from whatismyip but I'm not sure if I'm doing it correctly. Is something incorrect with my procedure?

回答1:

I am assuming you are trying to connect over the internet? If you are connected via some Internet provider like COMCAST then you probably have a cable modem? To do this sort of thing you are going to need to setup PORT forwarding on a router.

The internet only see's your cable modem, all your requests to the internet go out as your cable modems IP, the router is able to "route" packets to and from your 192.168.x.x address on your behalf, so in order to have your 192.168 machine be able to listen and accept you must tell your router to forward any messages on port 51328 to your machine.

So your code would listen to port 51328 using the 192.168.x.xx address, then you setup the router. To test it you would connect using the public internet address that is assigned to your modem.